C++实现访问者模式代码

时间:2024-04-13 18:39:45
#include <iostream>
#include <string>
#include <vector>
 
// 元素基类
class Element {
public:
    virtual void Accept(class Visitor& visitor) = 0;
    virtual ~Element() {}
};
 
// 具体元素
class ConcreteElementA : public Element {
public:
    void Accept(class Visitor& visitor) override {
        visitor.VisitConcreteElementA(this);
    }
    
    void OperationA() {
        std::cout << "ConcreteElementA OperationA" << std::endl;
    }
};
 
class ConcreteElementB : public Element {
public:
    void Accept(class Visitor& visitor) override {
        visitor.VisitConcreteElementB(this);
    }
    
    void OperationB() {
        std::cout << "ConcreteElementB OperationB" << std::endl;
    }
};
 
// 访问者基类
class Visitor {
public:
    virtual void VisitConcreteElementA(ConcreteElementA* element) = 0;
    virtual void VisitConcreteElementB(ConcreteElementB* element) = 0;
    virtual ~Visitor() {}
};
 
// 具体访问者
class ConcreteVisitor : public Visitor {
public:
    void VisitConcreteElementA(ConcreteElementA* element) override {
        element->OperationA();
    }
    
    void VisitConcreteElementB(ConcreteElementB* element) override {
        element->OperationB();
    }
};
 
int main() {
    // 创建元素对象
    std::vector<Element*> elements;
    elements.push_back(new ConcreteElementA());
    elements.push_back(new ConcreteElementB());
 
    // 创建访问者对象
    Visitor* visitor = new ConcreteVisitor();
 
    // 访问元素
    for (Element* elem : elements) {
        elem->Accept(*visitor);
    }
 
    // 清理
    for (Element* elem : elements) {
        delete elem;
    }
    delete visitor;
 
    return 0;
}