1. 概述
Proxy Patter模式:通过对某个对象提供代理,从而控制&隔离对这个对象的访问。
类图:
Object:定义了Concrete_object和Proxy的公用接口,这样才能在需要使用Concrete_object的地方使用Proxy代替
Concrete_object:具体实现类
Proxy:Concrete_object的代理
Proxy Pattern常使用在:
1)通过Proxy类,实现对Concrete_object访问的权限控制
2)隔离client和Concrete_object
3)处理数据库、中间件及其它第三方接口
Proxy Patter模式:通过对某个对象提供代理,从而控制&隔离对这个对象的访问。
类图:
Concrete_object:具体实现类
Proxy:Concrete_object的代理
Proxy Pattern常使用在:
1)通过Proxy类,实现对Concrete_object访问的权限控制
2)隔离client和Concrete_object
3)处理数据库、中间件及其它第三方接口
2. 实例
餐馆有普通用户和vip用户之分,对于vip用户,菜价8折。具体菜属于concrete_object,对菜价的控制通过proxy实现。
ok,let's go:
#include <iostream> #include <list> #include <algorithm> using namespace std; //Customer类,包括用户类别属性 class Customer { public: Customer(int type) { _type = type; } int get_type() { return _type; } private: int _type; //1为普通用户,2为VIP用户 }; //Object类 class Food { public: Food() { } virtual ~Food() { } virtual int price() = 0; virtual void set_customer(Customer*) { } }; //Concrete_object class Chinese_food : public Food { public: Chinese_food(int price) { _price = price; } virtual ~Chinese_food() { } virtual int price() { return _price; } private: int _price; }; //代理类 class Proxy_CF : public Food { public: Proxy_CF() { _cf = NULL; _customer = NULL; } virtual ~Proxy_CF() { if(_cf) { delete _cf; } } //根据用户的不同属性,给出具体的价格信息 virtual int price() { if(NULL == _cf) { _cf = new Chinese_food(100); } switch(_customer->get_type()) { case 1 : return _cf->price(); break; case 2: return (int)(0.8 * _cf->price()); break; default: return _cf->price(); break; } return _cf->price(); } void set_customer(Customer* customer) { _customer = customer; } private: Chinese_food* _cf; Customer* _customer; }; int main(int argc, char** argv) { Food* proxy_cf = new Proxy_CF()
输出:Customer c_a(1); proxy_cf->set_customer(&c_a); cout << "food price:" << proxy_cf->price() << endl; Customer c_b(2); proxy_cf->set_customer(&c_b); cout << "food price:" << proxy_cf->price() << endl; if(proxy_cf) { delete proxy_cf; } return 0; }
food price:100
food price:80