图片引用于百度
简介:由于某些原因需要给某对象提供一个代理以控制对该对象的访问。
这时,访问对象不适合或者不能直接引用目标对象,代理对象作为访问对象和目标对象之间的中介
优点:代理模式将客户端与目标对象分离,增加了程序的可扩展性
缺点:代理模式会造成系统设计中类的数量增加,效率降低
例子背景:现在有人想买电脑,但是电脑的配置不同,不知道他钱够不够,vip能88折,这里借用装饰者模式的代码作为产品
概念:把它比作房子中介,他介于顾客和包租公之间,处理一切事物
代理模式代码:
- 人类:
#pragma once
#include "../Decorator/Mainframe.h"
class People
{
public:
People() {}
~People() { delete m_mianFrame; }
public:
void SetMoney(double money) { m_money = money; }
void SetVip(bool vip) { m_isVip = vip; }
void SetName(const string& n) { m_name = n; }
double GetMoney() const { return m_money; }
bool isVip() const { return m_isVip; }
string GetName() const { return m_name; }
bool isHaveMainframe() const { return m_mianFrame; }
void SetMainframe(Mainframe* mf) { m_mianFrame = mf; }
private:
double m_money = 0;
bool m_isVip = false;
string m_name;
Mainframe* m_mianFrame = nullptr;
};
- 代理类:
#pragma once
#include "People.h"
class Proxy
{
public:
Proxy() {}
~Proxy() {}
public:
void BuyMainFrame(People* people, Mainframe* mf)
{
if (people->GetMoney() < mf->GetPrice())
{
cout << people->GetName() << "不能买主机,钱不够,继续赚钱吧" << endl;
return;
}
double totalPrice = mf->GetPrice();
string isVip("不是Vip");
if (people->isVip())
{
totalPrice *= 0.88;
isVip = "是Vip";
}
people->SetMoney(people->GetMoney() - totalPrice);
cout << people->GetName() << isVip << ",购买了(" << mf->GetName() << ")后还剩" << people->GetMoney() << "元钱" << endl;
people->SetMainframe(mf);
}
};
- 引用:
#include "Proxy.h"
#include "../Decorator/i7Mainframe.h"
#include "../Decorator/AccessoriesHardDisk.h"
#include "../Decorator/AccessoriesMemoryBank.h"
int main()
{
People* zhangsan = new People;
zhangsan->SetMoney(8000);
zhangsan->SetName("张三");
People* lisi = new People;
lisi->SetMoney(20000);
lisi->SetName("李四");
People* wangwu = new People;
wangwu->SetMoney(20000);
wangwu->SetName("王五");
wangwu->SetVip(true);
Mainframe* i7 = new i7Mainframe;
Mainframe* i71 = new i7Mainframe;
Mainframe* ahd = new AccessoriesHardDisk(i7);
Mainframe* ahd1 = new AccessoriesHardDisk(i71);
Mainframe* amb = new AccessoriesMemoryBank(ahd1);
shared_ptr<Proxy> proxy(new Proxy);
proxy->BuyMainFrame(zhangsan, i7);
proxy->BuyMainFrame(lisi, ahd);
proxy->BuyMainFrame(wangwu, amb);
cout << zhangsan->GetName() << "是否拥有主机:" << (zhangsan->isHaveMainframe() ? "是" : "否") << endl;
cout << lisi->GetName() << "是否拥有主机:" << (lisi->isHaveMainframe() ? "是" : "否") << endl;
cout << wangwu->GetName() << "是否拥有主机:" << (wangwu->isHaveMainframe() ? "是" : "否") << endl;
delete zhangsan;
delete lisi;
delete wangwu;
getchar();
return 0;
}
总结:
代理者模式(Proxy):代理者模式能够起到一个中介的作用,包办一切,在客户和售卖者之前来回奔波,值得注意的是,代理模式和适配器模式不同,它并不能改变所代理的类接口,它只是为了加强控制
作者:丶梦爱
博客:https://blog.csdn.net/u014732297(转载请说明出处)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)