设计模式之访问者模式

//设计模式之访问者模式
//将操作与数据结构分离开来。适用于数据结构不变,算法经常变化的情况。
#include<iostream>
#include<list>

using namespace std;

class Man;
class Woman;

class Action
{
public:
    virtual void getManCon(Man *man) = 0;
    virtual void getWomanCon(Woman* woman) = 0;
};

class Success :public Action
{
public:
    void getManCon(Man* man)
    {
        cout << "男人成功时,背后多半有一个伟大的女人" << endl;
    }
    void getWomanCon(Woman* woman)
    {
        cout << "女人成功时,别后多半有功不成功的男人," << endl;
    }
};

class Fail :public Action
{
public:
    void getManCon(Man *man)
    {
        cout << "男人失败时,闷头喝酒,谁也不用劝" << endl;
    }
    void getWomanCon(Woman* woman)
    {
        cout << "女人失败是" << endl;
    }
};

class People
{
public:
    virtual void Accept(Action *visitor) = 0;
};

class Man :public People
{
public:
    void Accept(Action* visitor)
    {
        visitor->getManCon(this);
    }
};

class Woman :public People
{
public:
    void Accept(Action* visitor)
    {
        visitor->getWomanCon(this);
    }
};

class Objcstructure
{
    list<People*> link;
    list<People*>::iterator it;
public:
    void AddLink(People* people)
    {
        link.push_back(people);
    }
    void Detach(People* people)
    {
        link.remove(people);
    }
    void Display(Action* visitor)
    {
        for (it = link.begin(); it != link.end(); it++)
        {
            (*it)->Accept(visitor);
        }
    }
};

int main()
{
    Objcstructure* ob = new Objcstructure();

    ob->AddLink((new Man));
    ob->AddLink((new Woman));

    Action *success = new Success();
    ob->Display(success);

    Action *fail = new Fail();
    ob->Display(fail);

    system("pause");
    return 0;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值