Benjamin

静以修身,俭以养德,非澹薄无以明志,非宁静无以致远。
随笔 - 388, 文章 - 0, 评论 - 196, 引用 - 0
数据加载中……

设计模式之Proxy模式和State模式

Proxy模式和State模式,都是提供一个Srurogate代理类,代码只与代理类打交道,实际工作的类隐藏在代理类的后面。调用代理类中的一个方法时,仅仅是调用实现类中相应的方法。
基本思想:Surrogate代理类派生自一个基类,实现类和代理类一样派生自相同的基类。
Proxy模式和State模式区别:结构上,Proxy模式只有一个实现类,State模式有多个;应用上,Proxy控制实现类的访问,State模式动态改变实现类。

Proxy模式的示例代码:
#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; }
  // Forward calls to the implementation:
  void f() { implementation->f(); }
  void g() { implementation->g(); }
  void h() { implementation->h(); }
};

int main()  {
  Proxy p;
  p.f();
  p.g();
  p.h();
}
在某些情况下,Implementtation并不需要和类Proxy有相同的接口,这意味着Proxy类可以任意关联Implementation类并将函数调用提交给它。使用共同接口的好处:可以把代理的替代物放到客户代码中,另外通过共同的接口,Iplementation被迫实现Proxy所需要的方法。代理模式用途:
Remote Proxy:远程代理,为在不同的地址空间的对象提供代理,通过远程代理对象实现。
Virtual Proxy:虚拟代理,即lazy initialization;
Protection Proxy:保护代理,如果不想客户程序员拥有被代理对象的所有访问权限时使用。
Smart Proxy:智能保护,renference counting引用计数就是一个离子,更简单的是对特定函数进行引用计数。

State模式:产生一个可以改变其类的对象,它在所有的函数都有条件代码时比较有用。
例子代码:bool变量的实现
class Creature {
  bool isFrog;
public:
  Creature() : isFrog(true) {}
  void greet() {
    if(isFrog)
      cout << "Ribbet!" << endl;
    else
      cout << "Darling!" << endl;
  }
  void kiss() { isFrog = false; }
};

int main() {
  Creature creature;
  creature.greet();
  creature.kiss();
  creature.greet();
}
所有的函数执行操作前都要测试isForg,通过State模式,就可以避免这样的情况。
下面是用State模式实现的代码:
#include <iostream>
#include <string>
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 2009-04-12 12:31 Benjamin 阅读(506) 评论(0)  编辑 收藏 引用 所属分类: C/C++


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