设计模式---访问者模式

来源:互联网 发布: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);
}






原创粉丝点击