Just enjoy programming

c++设计模式(三)代理模式(Proxy)与状态模式(State)模式

      代理(Proxy)模式,状态(State)模式都提供一个代理类。代码与代理类打交道,而实际工作的类隐藏在代理类背后。当调用代理类中的一个函数时,代理类仅转而去调用实现类中的相应的函数。这两种模式是如此相似,从结构上看,可以认为代理模式只是状态模式的一个特例。但是这两个模式的内涵是不一样的。
      基本思想很简单:代理类派生来自一个基类,由平行地派生来自同一个基类的一个或多个类提供实际的实现。当一个代理对象被创建的时候,一个实现对象就分配给了它,代理对象就将函数调用发给实现对象。
      从结构上来看,代理模式和状态模式的区别很简单:代理模式只有一个实现类,而状态模式有多个(一个以上)实现。认为这两种设计模式的应用也不同:代理模式控制对其实现类的访问,而状态模式动态地改变其实现类。
(1)代理模式例子:
#include<iostream>

using namespace std;

class ProxyBase
{
    public:
        virtual void f()=0;
        virtual void g()=0;
        virtual void h()=0;
        virtual ~ProxyBase(){}
};


class Implementation :public ProxyBase
{
    public:
        void f(){cout<<"Implementation.f()"<<endl;}
        void g(){cout<<"Implementation.g()"<<endl;}
        void h(){cout<<"Implementation.h()"<<endl;}
};


class Proxy: public ProxyBase
{
    ProxyBase *implementation;
    public:
        Proxy(){implementation=new Implementation();}
        ~Proxy(){delete implementation;}


        void f(){implementation->f();}
        void g(){implementation->g();}
        void h(){implementation->h();}
};

int main()
{
    Proxy p;
    p.f();
    p.g();
    p.h();
}

(2)状态模式
#include<iostream>

using namespace std;

class Creature
{
    class State
    {
        public:
            virtual string response()=0;
    };

    class Frog : public State
    {
        public:
            string response(){return "Ribbet!";}
    };

    class Prince:public State
    {
        public:
            string response(){return "Darling!";}
    };

    State *state;
    public:
        Creature(): state(new Frog()){}
        void greet()
        {
            cout<<state->response()<<endl;
        }
        void kiss()
        {
            delete state;
            state=new Prince();
        }
};


int main()
{
    Creature creature;
    creature.greet();
    creature.kiss();
    creature.greet();
}

posted on 2011-04-28 16:04 周强 阅读(698) 评论(0)  编辑 收藏 引用 所属分类: c/c++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理