#include "stdafx.h"
#include <iostream>
struct CEmployee;
struct CProgrammer;
struct CJuniorProgrammer;
struct CVeteranProgrammer;
struct CManager;
struct CCEO;
class IVisitor{
public:
virtual void Visit(CEmployee* p) = 0;
virtual void Visit(CProgrammer* p) = 0;
virtual void Visit(CJuniorProgrammer* p) = 0;
virtual void Visit(CVeteranProgrammer* p) = 0;
virtual void Visit(CManager* p) = 0;
virtual void Visit(CCEO* p) = 0;
};
#define FIRST_DISPATCH \
virtual void Accept(IVisitor *v){ v->Visit(this);}
#define SECOND_DISPATCH \
virtual void Visit(CEmployee* p ) {visit_helper(p);} \
virtual void Visit(CProgrammer* p ) {visit_helper(p);} \
virtual void Visit(CJuniorProgrammer* p ) {visit_helper(p);} \
virtual void Visit(CVeteranProgrammer* p) {visit_helper(p);} \
virtual void Visit(CManager* p ) {visit_helper(p);} \
virtual void Visit(CCEO* p ) {visit_helper(p);} \
struct CEmployee{
FIRST_DISPATCH
};
struct CProgrammer : public CEmployee{
FIRST_DISPATCH
};
struct CJuniorProgrammer : public CProgrammer{
FIRST_DISPATCH
};
struct CVeteranProgrammer : public CProgrammer{
FIRST_DISPATCH
};
struct CManager : public CEmployee{
FIRST_DISPATCH
};
struct CCEO : public CEmployee{
FIRST_DISPATCH
};
class SalaryVisitor:public IVisitor{
public:
//通过宏定义,帮助实现更便利的书写
SECOND_DISPATCH
//help函数的作用是:避免对每个子类都写代码
void visit_helper(CEmployee* p){
std::cout << "默认的算法,相当于default或者else" << std::endl;
}
void visit_helper(CProgrammer* p){
std::cout << "程序员基类。对一小类做“特殊处理”)" << std::endl;
}
void visit_helper(CCEO* p){
std::cout << "对具体的某个类做“特殊处理”)" << std::endl;
}
};
int main() {
IVisitor* pv = new SalaryVisitor();
CEmployee* pe = new CVeteranProgrammer();
pe->Accept(pv);
return 0;
}