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