1) 意图:
为其他对象提供一种代理以控制对这个对象的访问
2) 结构:
其中:
- Subject定义了 Proxy 和 RealSubject 的公有接口
- Proxy 保存一个引用,实现代理访问实体
- RealSubject定义了实体
3) 适用性:
- 复杂的指针代替简单的指针的时候,例如:远程代理、虚代理、保护代理...
4) 举例:
1 #include <iostream> 2 #include <list> 3 class Subject 4 { 5 public: 6 Subject() {} 7 virtual ~Subject() {} 8 virtual void Request() = 0; 9 }; 10 class RealSubject : public Subject 11 { 12 public: 13 RealSubject() {} 14 virtual ~RealSubject() {} 15 virtual void Request() 16 { 17 std::cout << "RealSubject request" << std::endl; 18 } 19 }; 20 class Proxy : public Subject 21 { 22 public: 23 Proxy():m_object(NULL) {} 24 virtual ~Proxy() 25 { 26 if (m_object) 27 { 28 delete m_object; 29 } 30 } 31 virtual void Request() 32 { 33 if (m_object == NULL) 34 { 35 m_object = new RealSubject(); 36 } 37 m_object->Request(); 38 } 39 private: 40 RealSubject* m_object; 41 }; 42 43 int main() 44 { 45 Subject* subject = new Proxy(); 46 subject->Request(); 47 system("pause"); 48 }