餐馆那些事之:Proxy Pattern

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)处理数据库、中间件及其它第三方接口

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值