
#include <vector>
#include <iostream>
#include <memory>
using namespace std;
class Engine;
class Wheel;
class Car;
//Visitor
class CarVisitor {
public:
virtual ~CarVisitor() = default;
virtual void visit(Engine* engine) = 0;
virtual void visit(Wheel* wheel) = 0;
virtual void visit(Car* car) = 0;
};
class Element {
public:
virtual ~Element() = default;
virtual void accept(CarVisitor* v) = 0;
};
//ConcreteElement
class Engine: public Element {
public:
void accept(CarVisitor* v) override {
v->visit(this);
}
};
//ConcreteElement
class Wheel: public Element {
private:
int number;
public:
explicit Wheel(int number)
: number(number) {}
int getNumber() {
return number;
}
void accept(CarVisitor* v) override {
v->visit(this);
}
};
//ConcreteElement
class Car: public Element {
private:
vector<unique_ptr<Element>> items;
public:
Car() {
items.push_back(make_unique<Engine>());
for (int i = 1; i <= 4; i++) {
items.push_back(make_unique<Wheel>(i));
}
}
void accept(CarVisitor* v) override {
for (const unique_ptr<Element>& e : items) {
e->accept(v);
}
v->visit(this);
}
};
//ConcreteVisitor
class TestCarVisitor: public CarVisitor {
public:
void visit(Engine*) override {
cout << "test engine\n";
}
void visit(Wheel* wheel) override {
cout << "test wheel #" <<
wheel->getNumber() << "\n";
}
void visit(Car*) override {
cout << "test car\n";
}
};
//ConcreteVisitor
class RepairCarVisitor: public CarVisitor {
public:
void visit(Engine*) override {
cout << "repair engine\n";
}
void visit(Wheel* wheel) override {
cout << "repair wheel #" <<
wheel->getNumber() << "\n";
}
void visit(Car*) override {
cout << "repair car\n";
}
};
//Client
Car car;
TestCarVisitor v1;
RepairCarVisitor v2;
car.accept(&v1);
//printed: test engine
// test wheel #1
// test wheel #2
// test wheel #3
// test wheel #4
// test car
car.accept(&v2);
//printed: repair engine
// repair wheel #1
// repair wheel #2
// repair wheel #3
// repair wheel #4
// repair car
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.Read more问题。一份文档由段落、图片和表格组成。程序必须能导出文档、统计字数并检查拼写。如果把每个操作都作为方法加到每一种组成部分上,每增加一个操作,这些部分的类就膨胀一次。而且一个操作的代码还会分散在许多类中。 思路。每个操作都变成一个单独的对象,称为访问者。访问者为每一种元素各准备一个方法。每个元素有一个方法,它接收一个访问者,并调用访问者中对应自己种类的方法。这样,每一对元素和操作都会运行正确的代码,无需检查类型。要增加一个新操作,只需编写一个新的访问者;元素类保持不变。 如何阅读示例。元素分为几种。每个具体访问者是一个操作,为每一种元素各有一个单独的方法。客户端代码把访问者交给元素,每个元素再把它送到对应自己种类的方法。在大多数示例中,一个元素包含其他元素,并把访问者交给自己的每个组成部分。随后两个访问者依次经过同样的这些部分,各自执行自己的操作。在某些语言中,元素是带有类型标签的普通数据,访问者是一个函数,为每一种元素各有一个版本。 何时使用。当元素类的集合保持稳定、而针对它们的新操作经常出现时,使用访问者模式。经常增加新的元素种类时不要使用它:每增加一种元素,每个访问者都需要一个新方法。 常见错误。在一个通用的访问者方法内部用条件判断检查元素的类型。这样,新的元素种类会在毫无警告的情况下被遗漏。应为每一种元素提供它自己的方法。 |