c++访问者模式
2021-02-19 本文已影响0人
一路向后
1.访问者模式简介
在访问者模式(Visitor Pattern)中,我们使用了一个访问者类,它改变了元素类的执行算法。通过这种方式,元素的执行算法可以随着访问者改变而改变。
2.源码实现
#include <iostream>
#include <string>
#include <list>
using namespace std;
class Element;
class Visitor
{
public:
virtual void Visit(Element *element){};
};
class Element
{
public:
virtual void Accept(Visitor *visitor){};
};
class Employee : public Element
{
public:
string name;
double income;
int vacationDays;
Employee(string name, double income, int vacationDays)
{
this->name = name;
this->income = income;
this->vacationDays = vacationDays;
}
void Accept(Visitor *visitor)
{
visitor->Visit(this);
}
};
class IncomeVisitor : public Visitor
{
public:
void Visit(Element *element)
{
Employee *employee = ((Employee *)element);
employee->income *= 1.10;
cout << employee->name << "'s new income: " << employee->income << endl;
}
};
class VacationVisitor : public Visitor
{
public:
void Visit(Element *element)
{
Employee *employee = ((Employee *)element);
employee->vacationDays += 3;
cout << employee->name << "'s new vacation days: " << employee->vacationDays << endl;
}
};
class Employees
{
private:
list<Employee *> employees;
public:
void Attach(Employee *employee)
{
employees.push_back(employee);
}
void Detach(Employee *employee)
{
employees.remove(employee);
}
void Accept(Visitor *visitor)
{
for(list<Employee *>::iterator it=employees.begin(); it!=employees.end(); it++)
{
(*it)->Accept(visitor);
}
}
};
int main(int argc, char **argv)
{
Employees *e = new Employees();
e->Attach(new Employee("Tom", 25000.0, 14));
e->Attach(new Employee("Thomas", 35000.0, 16));
e->Attach(new Employee("Roy", 45000.0, 21));
IncomeVisitor *v1 = new IncomeVisitor();
VacationVisitor *v2 = new VacationVisitor();
e->Accept(v1);
e->Accept(v2);
return 0;
}
3.编译源码
$ g++ -o example example.cpp
4.运行及其结果
$ ./example
Tom's new income: 27500
Thomas's new income: 38500
Roy's new income: 49500
Tom's new vacation days: 17
Thomas's new vacation days: 19
Roy's new vacation days: 24