案例:男人和女人对成功,失败,恋爱的表现不同
访问者模式
访问者模式简介(VisitorPattern)
通常具有访问者和被访问元素两个主要角色,被访问的元素常常具有固定种类不同的类型,不同的访问者可以对他们提供不同的访问方式。
访问者模式结构
- Visitor(抽象访问者): 声明具体元素的不同访问方法
- ConcreteVisitor(具体访问者): 实现对具体元素不同的访问方法
- Element(抽象元素): 声明accept()方法,以具体访问者作为参数传入
- ConcreteElement(具体元素): 具体要被访问的元素,实现accept()方法
- ObjectStructure(对象结构): 访问者可以访问到所有具体元素
访问者模式示例
https://gitee.com/NiMiKiss/design-pattern.git
#ifndef _VISITOR_PATTERN_
#define _VISITOR_PATTERN_
#include<iostream>
#include<vector>
class Person;
class Action
{
public:
virtual void GetManConclusion(Person* spPerson) = 0;
virtual void GetWomanConclusion(Person* spPerson) = 0;
};
class Person
{
public:
virtual void Accept(std::shared_ptr<Action> spAction) = 0;
};
class Man :public Person
{
public:
void Accept(std::shared_ptr<Action> spAction)
{
spAction->GetManConclusion(this);
}
};
class Woman :public Person
{
public:
void Accept(std::shared_ptr<Action> spAction)
{
spAction->GetWomanConclusion(this);
}
};
class Success :public Action
{
public:
void GetManConclusion(Person* spPerson)
{
std::cout << "男人成功时,背后多半是一个伟大的女人。" << std::endl;
}
void GetWomanConclusion(Person* spPerson)
{
std::cout << "女人成功时,背后多半是一个不成功的男人。" << std::endl;
}
};
class Fail :public Action
{
public:
void GetManConclusion(Person* spPerson)
{
std::cout << "男人失败时,闷头喝酒,谁也不用劝。" << std::endl;
}
void GetWomanConclusion(Person* spPerson)
{
std::cout << "女人失败时,眼泪汪汪,谁也劝不了。" << std::endl;
}
};
class Amativeness :public Action
{
public:
void GetManConclusion(Person* spPerson)
{
std::cout << "男人恋爱时,凡事不懂也要装懂。" << std::endl;
}
void GetWomanConclusion(Person* spPerson)
{
std::cout << "女人恋爱时,遇事懂也装作不懂。" << std::endl;
}
};
class ObjectStructure
{
public:
void Attach(std::shared_ptr<Person> spPerson)
{
m_vecPerson.push_back(spPerson);
}
void Detach(std::shared_ptr<Person> spPerson)
{
for (auto it = m_vecPerson.begin(); it != m_vecPerson.end(); ++it)
{
if (*it == spPerson)
{
m_vecPerson.erase(it);
}
}
}
void Display(std::shared_ptr<Action> spAction)
{
for (auto it = m_vecPerson.begin(); it != m_vecPerson.end(); ++it)
{
(*it)->Accept(spAction);
}
}
private:
std::vector<std::shared_ptr<Person>> m_vecPerson;
};
#endif // !_VISITOR_PATTERN_
客户端调用
#include "Visitor_Pattern.h"
#include<iostream>
int main()
{
auto spObjectStructure = std::shared_ptr<ObjectStructure>(new ObjectStructure());
auto spMan = std::shared_ptr<Man>(new Man());
auto spWoman = std::shared_ptr<Woman>(new Woman());
spObjectStructure->Attach(spMan);
spObjectStructure->Attach(spWoman);
auto spSuccess = std::shared_ptr<Success>(new Success());
auto spFail = std::shared_ptr<Fail>(new Fail());
auto spAmativeness = std::shared_ptr<Amativeness>(new Amativeness());
spObjectStructure->Display(spSuccess);
spObjectStructure->Display(spFail);
spObjectStructure->Display(spAmativeness);
return EXIT_SUCCESS;
}