码迷,mamicode.com
首页 > 其他好文 > 详细

访问器模式

时间:2017-05-19 23:57:27      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:begin   isp   virtual   push   意图   ios   blog   virt   alt   

访问器(visitor)模式

意图:主要将数据结构与数据操作分离。
主要解决:稳定的数据结构和易变的操作耦合问题。

代码:

#include <iostream>
#include <list>
using namespace std;

class ComputerPartVisitor;

class ComputerPart
{
public:
    virtual ~ComputerPart() {}
public:
    virtual void accept(ComputerPartVisitor *v) = 0;
};

class KeyBoard;
class Mouse;
class Monitor;

class ComputerPartVisitor
{
public:
    virtual ~ComputerPartVisitor() {}
public:
    virtual void visit(KeyBoard *keyboard) = 0;
    virtual void visit(Mouse *mouse) = 0;
    virtual void visit(Monitor *monitor) = 0;
};

class KeyBoard : public ComputerPart
{
public:
    virtual void accept(ComputerPartVisitor *v) 
    {
        v->visit(this);
    }
};

class Mouse : public ComputerPart
{
public:
    virtual void accept(ComputerPartVisitor *v)
    {
        v->visit(this);
    }
};

class Monitor : public ComputerPart
{
public:
    virtual void accept(ComputerPartVisitor *v)
    {
        v->visit(this);
    }
};

class ComputerPartDisplayVisitor : public ComputerPartVisitor
{
public:
    virtual void visit(KeyBoard *keyboard)
    {
        cout << "Displaying KeyBoard." << endl;
    }

    virtual void visit(Mouse *mouse)
    {
        cout << "Displaying Mouse." << endl;
    }

    virtual void visit(Monitor *monitor)
    {
        cout << "Displaying Monitor." << endl;
    }
};

class Computer
{
public:
    Computer()
    {
        _computerPartList.clear();
        addComponent(new KeyBoard);
        addComponent(new Mouse);
        addComponent(new Monitor);
    }

    ~Computer()
    {
        for (auto it = _computerPartList.begin(); it != _computerPartList.end(); ++it)
        {
            delete *it;
        }
        _computerPartList.clear();
    }

public:
    void addComponent(ComputerPart *cp)
    {
        _computerPartList.push_back(cp);
    }

    void accept(ComputerPartVisitor *v)
    {
        for (auto it = _computerPartList.begin(); it != _computerPartList.end(); ++it)
        {
            (*it)->accept(v);
        }
    }
private:
    list<ComputerPart*> _computerPartList;
};

void test()
{
    Computer *c = new Computer();
    ComputerPartVisitor *visitor = new ComputerPartDisplayVisitor();
    c->accept(visitor);
    delete c;
    delete visitor;
}

int main()
{
    test();
    cin.get();
    return 0;
}

效果:

技术分享

 

访问器模式

标签:begin   isp   virtual   push   意图   ios   blog   virt   alt   

原文地址:http://www.cnblogs.com/hupeng1234/p/6880446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!