對於復雜的軟件系統常常有一種處理手法,即增加一層間接層,從而使得系統獲得一種更為靈活、滿足特定需求的解決方案。在面向對象的系統中,有些對象由於某種原因,比如對象創建的開銷很大,或者某些操作需要安全控制,或者需要進程外的訪問等,直接訪問會給使用者或者系統結構帶來很多麻煩。
Proxy設計模式就是在不失去透明操作對象的同時,通過增加一層間接層來管理、控制這些對象特有的復雜性。
[cpp]
// Proxy.h
#include <string>
#include <iostream>
#include <string>
class IEmployee
{
public:
virtual string get_name(int ID) = 0;
virtual int get_age(int ID) = 0;
virtual double get_salary(int ID) = 0;
public:
virtual ~IEmployee();
};
IEmployee::~IEmployee()
{
cout << "in the destructor of IEmployee..." << endl;
}
class Employee : public IEmployee
{
public:
string get_name(int ID);
int get_age(int ID);
double get_salary(int ID);
~Employee();
};
string Employee::get_name(int ID)
{
// ... 假定此處查詢數據庫,獲得ID對應員工的姓名
string name = "tom";
return name;
}
int Employee::get_age(int ID)
{
// ... 假定此處查詢數據庫,獲得ID對應員工的年齡
int age = 20;
return age;
}
double Employee::get_salary(int ID)
{
// ... 假定此處查詢數據庫,獲得ID對應員工的工資
double salary = 100000.00;
return salary;
}
Employee::~Employee()
{
cout << "in the destructor of Employee..." << endl;
}
//代理
class EmployeeProxy : public IEmployee
{
public:
string get_name(int ID);
int get_age(int ID);
double get_salary(int ID);
~EmployeeProxy();
};
string EmployeeProxy::get_name(int ID)
{
// ...假定此處通過socket或者RPC等其他方式訪問Employee中的get_name(int ID)方法,並接受相應的返回值
string name = "tom";
return name;
}
int EmployeeProxy::get_age(int ID)
{
// ...假定此處通過socket或者RPC等其他方式訪問Employee中的get_age(int ID)方法,並接受相應的返回值
int age = 20;
return age;
}
double EmployeeProxy::get_salary(int ID)
{
// ...假定此處通過socket或者RPC等其他方式訪問Employee中的get_salary(int ID)方法,並接受相應的返回值
double salary = 100000.00;
return salary;
}
EmployeeProxy::~EmployeeProxy()
{
cout << "in the destructor of EmployeeProxy..." << endl;
}
// Proxy.cpp
#include "Proxy.h"
int main(int argc, char **argv)
{
IEmployee *employee = new EmployeeProxy;
cout << employee->get_name(10) << endl;
cout << employee->get_age(10) << endl;
cout << employee->get_salary(10) << endl;
delete employee;
return 0;
}