2.4 设计模式之动态代理模式+

动态代理模式+AOP

面向切片编程:关注方法执行前后变化

(c++代码)

// 对象接口
class ISubject
{
public:
	ISubject() {};
	virtual ~ISubject() {}

public:
	virtual void doSomething(std::string str) = 0;
};

// 通知
class IAdvice
{
public:
	IAdvice() {}
	~IAdvice() {}

public:
	virtual void exec() = 0;
};

// 实际对象
class realSubject:public ISubject
{
public:
	realSubject() {};
	virtual ~realSubject() {}

public:
	virtual void doSomething(std::string str) {
		std::cout << str.c_str() << std::endl;
	}
};

// 代理对象
class proxy :public ISubject
{
public:
	explicit proxy(ISubject* obj,IAdvice* before,IAdvice* after):subject(obj),before(before),after(after) {};
	virtual ~proxy() {
		delete subject;
		delete before;
		delete after;
	}

public:
	// aop doSomething
	virtual void doSomething(std::string str) {
		if (before != NULL) {
			before->exec();
		}
		if (subject != NULL) {
			subject->doSomething(str);
		}
		if (after != NULL) {
			after->exec();
		}
	}
private:
	ISubject* subject;
	IAdvice* before;
	IAdvice* after;
};

// 前置通知
class beforeAdvice: public IAdvice
{
public:
	beforeAdvice(){}
	~beforeAdvice() {}

public:
	virtual void exec() {
		std::cout << "执行前置操作" << std::endl;
	}
};

// 后置通知
class afterAdvice : public IAdvice
{
public:
	afterAdvice() {}
	~afterAdvice() {}

public:
	virtual void exec() {
		std::cout << "执行后置操作" << std::endl;
	}
};

// 动态代理
class dynamicProxy
{
private:
	dynamicProxy() {}
	~dynamicProxy() {}

public:
	static proxy* newProxyInstance(ISubject* obj,IAdvice* before, IAdvice* after) {
		return new proxy(obj, before, after);
	}
};

void test_dynamicProxy(){
	realSubject* rSub = new realSubject();

	proxy* agent = dynamicProxy::newProxyInstance(rSub, new beforeAdvice(), new afterAdvice());
	if (agent != NULL) {
		agent->doSomething("hello world!");
	}
	delete agent;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值