设计模式之——访问者模式

旧街凉风 提交于 2019-11-27 03:15:52

element.h

#ifndef ELEMENT_H
#define ELEMENT_H

#include "visitor.h"
class Element
{
public:
    Element() {}
    virtual void accept(Visitor *visitor) = 0;
};

class ConcreteElementA : public Element
{
public:
    ConcreteElementA() {}
    void accept(Visitor *visitor)
    {
        visitor->visitConcreteElementA(this);
    }
};

class ConcreteElementB : public Element
{
public:
    ConcreteElementB() {}
    void accept(Visitor *visitor)
    {
        visitor->visitConcreteElementB(this);
    }
};

#endif // ELEMENT_H

visitor.h

#ifndef VISITOR_H
#define VISITOR_H

#include <QtDebug>
#include "element.h"

class Element;
class ConcreteElementA;
class ConcreteElementB;

class Visitor
{
public:
    Visitor() {}
    virtual void visitConcreteElementA(ConcreteElementA *concreteElementA){}
    virtual void visitConcreteElementB(ConcreteElementB *concreteElementB){}
};

class ConcreteVisitor1 : public Visitor
{
public:
    ConcreteVisitor1() {}
    void visitConcreteElementA(ConcreteElementA *concreteElementA)
    {
        qDebug() << "ConcreteVisitor1 visitConcreteElementA";
    }

    void visitConcreteElementB(ConcreteElementA *concreteElementB)
    {
        qDebug() << "ConcreteVisitor1 visitConcreteElementB";
    }
};

class ConcreteVisitor2 : public Visitor
{
public:
    ConcreteVisitor2() {}
    void visitConcreteElementA(ConcreteElementA *concreteElementA)
    {
        qDebug() << "ConcreteVisitor2 visitConcreteElementB";
    }

    void visitConcreteElementB(ConcreteElementA *concreteElementB)
    {
        qDebug() << "ConcreteVisitor2 visitConcreteElementB";
    }
};

#endif // VISITOR_H

objectStructure.h

#ifndef OBJECTSTRUCTURE_H
#define OBJECTSTRUCTURE_H

#include <QList>
#include "element.h"
#include "visitor.h"

class ObjectStructure
{
public:
    ObjectStructure() {}
    void attach(Element *element)
    {
        m_elements.append(element);
    }
    void detach(Element *element)
    {
        for(int i = m_elements.count(); i > 0; i++)
        {
            if(m_elements.at(i-1) == element)
            {
                m_elements.removeAt(i-1);
            }
        }
    }

    void accept(Visitor *visitor)
    {
        foreach (Element *e, m_elements) {
            e->accept(visitor);
        }
    }
private:
    QList<Element*> m_elements;
};

#endif // OBJECTSTRUCTURE_H

main.cpp

#include <QApplication>
#include "objectStructure.h"
#include "element.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    ObjectStructure *o = new ObjectStructure();
    ConcreteElementA *aa = new ConcreteElementA();
    ConcreteElementB *bb = new ConcreteElementB();
    o->attach(aa);
    o->attach(bb);


    ConcreteVisitor1 *v1 = new ConcreteVisitor1();
    ConcreteVisitor2 *v2 = new ConcreteVisitor2();
    o->accept(v1);
    o->accept(v2);

    return a.exec();
}

UML
在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!