设计模式学习笔记-结构型模式-Proxy模式

设计模式学习笔记-结构型模式-Proxy模式_第1张图片Proxy.h

#pragma once

class Subject
{
public:
	Subject();
	~Subject();

	virtual void Request() = 0;
};

class ConcreteSubject :public Subject
{
public:
	ConcreteSubject();
	~ConcreteSubject();

	void Request();
};

class Proxy
{
public:
	Proxy(Subject* sub);
	~Proxy();

	void Request();

protected:
private:
	Subject* _sub;
};

Proxy.cpp

#include "Proxy.h"
#include 
using namespace std;


Proxy::Proxy(Subject * sub)
{
	_sub = sub;
}

Proxy::~Proxy()
{
	delete _sub;
}

void Proxy::Request()
{
	cout << "Proxy request...." << endl;
	_sub->Request();
}

ConcreteSubject::ConcreteSubject()
{
}

ConcreteSubject::~ConcreteSubject()
{
}

void ConcreteSubject::Request()
{
	cout << "ConcreteSubject......request...." << endl;
}

Subject::Subject()
{
}

Subject::~Subject()
{
}

main.cpp

#include 
#include "Proxy.h"
using namespace std;

int main(int argc, char* argv[])
{
	/*代理模式*/
	Subject* sub = new ConcreteSubject();
	Proxy* p = new Proxy(sub);
	p->Request();//p 的 Request 请求实际上是交给了 sub 来实际执行

	system("pause");
	return 0;
}
Proxy request....
ConcreteSubject......request....
请按任意键继续. . .

Proxy 模式最大的好处就是实现了逻辑和实现的彻底解耦。

你可能感兴趣的:(c++,设计模式,学习,代理模式)