动态代理模式+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;
}