设计模式---访问者模式
来源:互联网 发布:tcp ip网络编程 源码 编辑:程序博客网 时间:2024/06/09 16:58
访问者模式
表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
目的是要把处理从数据结构分离出来。
优点是增加新的操作很容易,因为增加新的操作就意味着增加一个新的访问者。访问者模式将有关的行为集中到一个访问者对象中。
#include<iostream>
#include<list>using namespace std;
class Action;
class Person
{
public:
virtual void Operation(Action *visitor){}
};
class Man;
class Woman;
class Action
{
public:
virtual void GetManConclusion(Man *concreteElementA){}
virtual void GetWomanConclusion(Woman *concreteElementA){}
};
class Man: public Person
{
public:
void Operation(Action *visitor);
};
void Man:: Operation(Action *visitor)
{
visitor->GetManConclusion(this);
}
class Woman: public Person
{
public:
void Operation(Action *visitor);
};
void Woman:: Operation(Action *visitor)
{
visitor->GetWomanConclusion(this);
}
class Success:public Action
{
public:
void GetManConclusion(Man *concreteElementA);
void GetWomanConclusion(Woman *concreteElementB);
};
void Success:: GetManConclusion(Man *concreteElementA)
{
cout<<" man suc " <<endl;
}
void Success::GetWomanConclusion(Woman *concreteElementB)
{
cout<<" woman suc "<<endl;
}
class Failing :public Action
{
public:
void GetManConclusion(Man *concreteElementA);
void GetWomanConclusion(Woman *concreteElementB);
};
void Failing :: GetManConclusion(Man *concreteElementA)
{
cout<<" man failing " <<endl;
}
void Failing ::GetWomanConclusion(Woman *concreteElementB)
{
cout<<" woman failing " <<endl;
}
class Loving :public Action
{
public:
void GetManConclusion(Man *concreteElementA);
void GetWomanConclusion(Woman *concreteElementB);
};
void Loving :: GetManConclusion(Man *concreteElementA)
{
cout<<" man loving "<<endl;
}
void Loving :: GetWomanConclusion(Woman *concreteElementB)
{
cout<<" woman loving " <<endl;
}
class ObjectStruture
{
private:
list<Person*> ele ;
public:
void Attach(Person *per)
{
ele.push_back(per);
}
void Detach(Person *per)
{
ele.remove(per);
}
void Display(Action *visitor)
{
for(list<Person*>::iterator it = ele.begin();it != ele.end();++it)
(*it)->Operation(visitor);
}
};
int main()
{
ObjectStruture *o = new ObjectStruture();
o->Attach(new Man());
o->Attach(new Woman());
Success *v1 = new Success();
o->Display(v1);
Failing *v2 = new Failing ();
o->Display(v2);
Loving *v3 = new Loving();
o->Display(v3);
}
阅读全文
0 0
- 设计模式 访问者模式
- 设计模式 - 访问者模式
- 设计模式:访问者模式
- 设计模式 - 访问者模式
- 设计模式 - 访问者模式
- 设计模式------------访问者模式
- 设计模式:访问者模式
- 设计模式--访问者模式
- 设计模式--访问者模式
- 设计模式-访问者模式
- 设计模式--访问者模式
- 设计模式-访问者模式
- 设计模式-访问者模式
- [设计模式]访问者模式
- 设计模式 - 访问者模式
- 设计模式-访问者模式
- 设计模式-访问者模式
- 设计模式-访问者模式
- 百度地图API示例之添加/删除工具条、比例尺控件
- Leetcode(16)
- WebView性能、体验分析与优化
- 开博客之初心
- 和菜鸟一起学电子小玩意之四轴飞行器原理
- 设计模式---访问者模式
- PuTTY (3) Serial port connection
- Visual Studio Code 让高效进行到底
- php多语言包
- (鸿洋)Android 6.0 运行时权限处理完全解析
- 《政府网站发展指引》发布,SSL证书保障政府网站安全
- AndroidStudio生成javadoc文件
- ngrok:简单好用的内网映射工具
- Java多线程之this与Thread.currentThread()的区别——java多线程编程核心技术