代理模式(Procy Pattern)
写在前面:
今天早上做了一件坏事。早上路过一个早餐店,发现门口有一辆摩拜单车,准备扫码来骑。马上走近单车了,从店里出来一个妹子,快步走过去想扫单车。这个时候我手机已经准备好了,就立马预约了单车。其实是出于好奇和好玩。我就看着妹子扫了很久没扫开,就快步小跑开了,看来是有急事。唉,实在不应该。
基本概念:
代理模式,顾名思义,就是利用一个类来代理另一个类所能实现的功能。属于结构型模式。
应用场合:
多数应用在“调用”场合。比如调用系统中的某个资源,调用远程的对象等。通过代理类能够获得被代理类的功能。
应用特点:
使用代理类,相当于给原有类添加了一层访问层。可以在这个访问层里添加用户想添加的一些功能,比如访问控制等。
应用举例:
就拿买车为例(又是车),现在有很多老赖,欠着外债不还,自己却过着逍遥的日子。对于老赖就该有惩罚措施,比如不能买车。有一个人想去买车,先要提交资料,由有关部门(?最厉害的部门?)审核。不是老赖,就批准买车。如果是老赖,嘿嘿,还是回去骑自行车吧
(-_-)。
上代码:
//销售员
//H
#pragma once
#include <iostream>
#include <assert.h>
#include <string>
using namespace std;
class carsales
{
public:
carsales(void);
virtual ~carsales(void);
virtual void feedback() = 0;
};
//CPP
#include "carsales.h"
carsales::carsales(void)
{
}
carsales::~carsales(void)
{
}
//代理
//H
#pragma once
#include "carsales.h"
#include "aseller.h"
class proxysaller : public carsales
{
public:
proxysaller(unsigned int _score);
~proxysaller(void);
void feedback();
private:
unsigned int score;
aseller* ababy;
};
//CPP
#include "proxysaller.h"
proxysaller::proxysaller(unsigned int _score)
{
score = _score;//not use
ababy = new aseller(_score);
}
proxysaller::~proxysaller(void)
{
}
void proxysaller::feedback()
{
ababy->feedback();
}
//测试
#include <iostream>
#include "aseller.h"
#include "proxysaller.h"
int main()
{
int bryan = 59;
int hope = 61;
cout<<"Bryan:"<<endl;
proxysaller *agent = new proxysaller(bryan);
agent->feedback();
delete agent;
agent = NULL;
cout<<"Hope:"<<endl;
agent = new proxysaller(hope);
agent->feedback();
delete agent;
return 0;
}

本文介绍了代理模式的基本概念及其应用场景,通过购车实例展示了如何使用代理模式进行访问控制,并提供了一个简单的C++代码示例。

7790

被折叠的 条评论
为什么被折叠?



