C++设计模式:访问者模式

一、源代码:

#include
#include
#include

using namespace std;

class Computer;
class Mouse;
class Keyboard;
class Monitor;
class ComputerPartVisitor
{
public:
    virtual void visit(shared_ptr computer) = 0;
    virtual void visit(shared_ptr mouse) = 0;
    virtual void visit(shared_ptr keyboard) = 0;
    virtual void visit(shared_ptr monitor) = 0;
    virtual ~ComputerPartVisitor() = default;
};

class ComputerPartDisplayVisitor:public ComputerPartVisitor
{
public:
    virtual void visit(shared_ptr computer) override
    {
        cout<<"Displaying Computer."< mouse) override
    {
        cout<<"Displaying Mouse."< keyboard) override
    {
        cout<<"Displaying Keyboard."< monitor) override
    {
        cout<<"Displaying Monitor."< computerPartVisitor) = 0;
    virtual ~ComputerPart() = default;
};

class Keyboard:public ComputerPart
{
public:
    virtual void accept(shared_ptr computerPartVisitor) override
    {
        computerPartVisitor->visit(make_shared(*this));
    }
};

class Monitor:public ComputerPart
{
public:
    virtual void accept(shared_ptr computerPartVisitor) override
    {
        computerPartVisitor->visit(make_shared(*this));
    }
};

class Mouse:public ComputerPart
{
public:
    virtual void accept(shared_ptr computerPartVisitor) override
    {
        computerPartVisitor->visit(make_shared(*this));
    }
};

class Computer:public ComputerPart
{
public:
    virtual void accept(shared_ptr computerPartVisitor) override
    {
        vector> parts = {make_shared(),make_shared(),make_shared()};
        for(const auto& part:parts)
        {
            part->accept(computerPartVisitor);
        }
        computerPartVisitor->visit(make_shared(*this));
    }
};

int main()
{
    shared_ptr computer = make_shared();
    computer->accept(make_shared());
}

二、运行结果:

C++设计模式:访问者模式_第1张图片

三、吐槽:

绕的头晕,只用一个C++文件,问题很多,以后尽量不要设计写这种来回嵌套的类——两个类的定义互相包含对方,不利于维护,要降低耦合度,单向依赖

你可能感兴趣的:(C++)