基本介紹
- 中文名:代理模式
- 外文名:Proxy Pattern
- 組成:抽象角色、代理角色、真實角色
- 優點:職責清晰
簡介
組成
優點
模式結構
對象實現同一個接口,先訪問代理類再訪問真正要訪問的對象。
代碼示例
#include <iostream>using namespace std;class RealImage { int m_id; public: RealImage(int i) { m_id = i; cout << " $$ ctor: " << m_id << '\n'; } ~RealImage() { cout << " dtor: " << m_id << '\n'; } void draw() { cout << " drawing image " << m_id << '\n'; }};// 1. Design an "extra level of indirection" wrapper classclass Image{// 2. The wrapper class holds a pointer to the real class RealImage *m_the_real_thing; int m_id; static int s_next; public: Image() { m_id = s_next++; // 3. Initialized to null m_the_real_thing = 0; } ~Image() { delete m_the_real_thing; } void draw() { // 4. When a request comes in, the real object is // created "on first use" if (!m_the_real_thing) m_the_real_thing = new RealImage(m_id); // 5. The request is always delegated m_the_real_thing->draw(); }}; int Image::s_next = 1; int main() { Image images[5]; for (int i; true;) { cout << "Exit[0], Image[1-5]: "; cin >> i; if (i == 0) break; images[i - 1].draw(); } system("Pause");};