设计模式--访问者模式

访问者模式:属于行为型模式
基本原理:元素类的执行算法随着访问者改变而改变。
主要流程:
            1.创建元素类,内有不同的执行算法,根据不同的访问者选择不同的执行算法
            2.创建访问类,实现不同的访问派生类,将自身传入元素类的执行算法

#include 
#include 
#include 

using namespace std;

class Keyboard;
class Monitor;
class Mouse;
class Computer;

//创建元素类
class ComputerPartVisitor
{
public:
    virtual void visit(Computer *computer) = 0;
    virtual void visit(Monitor *monitor) = 0;
    virtual void visit(Keyboard *keyboard) = 0;
    virtual void visit(Mouse *mouse) = 0;
};

//创建访问类
class ComputerPart
{
public:
    virtual void accept(ComputerPartVisitor *computerPartVisitor) = 0;
};
//访问类的不同派生类
class Keyboard : public ComputerPart
{
public:
    void accept(ComputerPartVisitor *computerPartVisitor)
    {
        computerPartVisitor->visit(this);
    }
};
class Monitor : public ComputerPart
{
public:
    void accept(ComputerPartVisitor *computerPartVisitor)
    {
        computerPartVisitor->visit(this);
    }
};
class Mouse : public ComputerPart
{
public:
    void accept(ComputerPartVisitor *computerPartVisitor)
    {
        computerPartVisitor->visit(this);
    }
};
class Computer : public ComputerPart
{
public:
    vector parts;
    Computer()
    {
        this->parts.push_back(new Keyboard());
        this->parts.push_back(new Monitor());
        this->parts.push_back(new Mouse());
    }
    void accept(ComputerPartVisitor *computerPartVisitor)
    {
        for(int i=0; iaccept(computerPartVisitor);
        }
        computerPartVisitor->visit(this);
    }
};

//元素类的派生类
class ComputerPartDisplayVisitor : public ComputerPartVisitor
{
    void visit(Computer *computer)
    {
        cout<<"Displaying Computer!"<accept(new ComputerPartDisplayVisitor());
    return 0;
}

 

你可能感兴趣的:(设计模式)