設計模式之訪問者模式

訪問者模式表示一個作用於某對象結構中的各元素的操作,它使你可以在不改變類的前提下定義作用於這些元素的操作。
訪問者模式的目的是要把處理從數據結構分離出來。很多系統可以按照算法和數據結構分開,如果這樣的系統有比較穩定的數據結構,又有易於變化的算法的話,使用訪問者模式就是比較合適的。
UML圖如下:
這裏寫圖片描述
代碼如下:

class Action
{
public:
    Action() {}
    virtual ~Action() {}
    virtual void GetManConclusion(Man* __m) {}
    virtual void GetWomanConclusion(Woman* __w) {}
};
class Amativeness : public Action
{
public:
    Amativeness() {}
    ~Amativeness() {}
    virtual void GetManConclusion(Man* __m)
    {
        std::cout << typeid(__m).name() << typeid(this).name() << ",KNOW." << std::endl;
    }
    virtual void GetWomanConclusion(Woman* __w)
    {
        std::cout << typeid(__w).name() << typeid(this).name() << ",NOT KNOW." << std::endl;
    }
};
class Failing : public Action
{
public:
    Failing() {}
    ~Failing() {}
    virtual void GetManConclusion(Man* __m)
    {
        std::cout << typeid(__m).name() << typeid(this).name() << ",Drink." << std::endl;
    }
    virtual void GetWomanConclusion(Woman* __w)
    {
        std::cout << typeid(__w).name() << typeid(this).name() << ",Cry." << std::endl;
    }
};
class Success : public Action
{
public:
    Success() {}
    ~Success() {}
    virtual void GetManConclusion(Man* __m)
    {
        std::cout << typeid(__m).name() << typeid(this).name() << ",have a great woman."<<std::endl;
    }

    virtual void GetWomanConclusion(Woman* __w)
    {`這裏寫代碼片`
        std::cout << typeid(__w).name() << typeid(this).name() << ",do not have a great man." << std::endl;
    }
};
class Person
{
public:
    Person() {}
    virtual ~Person() {}

    virtual void Accept(Action* visitor)
    {

    }
};
class Woman : public Person
{
public:
    Woman() { }
    ~Woman() {}
    virtual void Accept(Action* visitor)
    {
        visitor->GetWomanConclusion( this);
    }
};
class Man : public Person
{
public:
    Man(){ }
    ~Man() {}
    virtual void Accept(Action* visitor)
    {
        visitor->GetManConclusion(this);
    }
};
class ObjectStructure
{
private:

    std::list<Person*> elements;
public:
    ObjectStructure() {}
    ~ObjectStructure()
    {
        elements.clear();
    }

    void Attach(Person* __p)
    {
        elements.push_back(__p);
    }

    void Detach(Person* __p)
    {
        elements.remove(__p);
    }

    void Display(Action* vistor)
    {
        for each (Person* __p in elements)
        {
            __p->Accept(vistor);
        }
    }

};
//客戶端代碼
ObjectStructure obj;
    Person* pMan = new Man();
    Person* pWoman = new Woman();
    obj.Attach(pMan);
    obj.Attach(pWoman);

    Action* pSuc = new Success();
    obj.Display(pSuc);

    Action* pFail = new Failing();
    obj.Display(pFail);

    Action* pAmative = new Amativeness();
    obj.Display(pAmative);

運行結果如下:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章