definition
Provides a proxy for other objects to control (isolate, use interfaces) access to this object. .
Application Scenario
- In an object-oriented system, direct access to some objects for some reason (for example, the overhead of object creation is very high, or certain operations require security control, or requires out-of-process access, etc.) will bring a lot of problems to the user or the system structure. trouble.
- How to manage/control the unique complexity of operating objects without losing transparency? Adding a layer of indirection is a common solution in software development.
structure
//test.cpp
/****************************************************/
#include "Proxy.h"
int main()
{
// 玩魔兽
ProxyWOW* proxy = new ProxyWOW();
// 加载
proxy->load();
// 充值
proxy->recharge(1000);
// 加载
proxy->load();
// 退出
proxy->exit();
// 清理内存
delete proxy;
proxy = nullptr;
return 0;
}
code example
//Proxy.h
/****************************************************/
#ifndef PROXY_H
#define PROXY_H
#include <iostream>
using namespace std;
// 抽象游戏类
class Game
{
public:
// 游戏加载
virtual void load() = 0;
// 游戏退出
virtual void exit() = 0;
};
// 真实游戏类-魔兽世界
class WOW : public Game
{
public:
// 游戏加载
virtual void load() {
cout << "魔兽世界加载。" << endl;
}
// 游戏退出
virtual void exit() {
cout << "魔兽世界退出。" << endl;
}
};
// 代理类-魔兽代理
class ProxyWOW : public Game
{
public:
// 构造函数
ProxyWOW() {
m_wow = new WOW();
}
// 析构函数
virtual ~ProxyWOW() {
if (m_wow != nullptr) {
delete m_wow;
m_wow = nullptr;
}
}
// 充值时间
void recharge(int money) {
m_time += money / 100;
cout << "充值:" << money << endl;
cout << "获得时长:" << m_time << endl;
}
// 游戏加载
virtual void load() {
cout << "代理启动。" << endl;
if (m_time > 0) {
m_wow->load();
cout << "游戏时长1小时。" << endl;
m_time -= 1;
cout << "剩余时长:" << m_time << endl;
flag = true;
}
else {
cout << "剩余游戏时长不足,请充值。" << endl;
flag = false;
}
}
// 游戏退出
virtual void exit() {
if (flag) {
m_wow->exit();
flag = false;
}
cout << "代理关闭。" << endl;
}
private:
bool flag = false;
int m_time = 0;
WOW* m_wow;
};
#endif
operation result
Summary
- "Adding a layer of indirection" is a common solution to many complex problems in software systems. In an object-oriented system, using some objects directly will bring many problems, and the proxy object as an indirect layer is a common means to solve this problem.
- The implementation methods and implementation granularity of the specific proxy design pattern vary greatly. Some may implement fine-grained control over a single object, such as copy-on-write technology. proxy.
- Proxy does not necessarily require to maintain the complete consistency of the interface, as long as indirect control can be achieved, sometimes it is acceptable to damage some transparency.