AOP (aspect-oriented programming) is the Java technology, Java is implemented through the reflection mechanism, C + + does not have a Java-like reflection mechanism, there is no way to implement like Java. Some open source projects already implement C + + AOP, such as aspectc++, but it needs to use a special compiler to compile, syntax is no longer C + + syntax, more complex to use, here, I through the characteristics of C + + to implement AOP.
Implementation principle:
encapsulates an interface class (Action) with a smart pointer-like class (Baseaspect) that uses the characteristics of the anonymous object lifecycle to implement AOP.
Key Features:
1, the construction of C + + objects and the call mechanism of destructors: When objects are created, when objects are destroyed, they are constructed.
2. The life cycle of an anonymous object is in a statement: created at the time the object is defined and destroyed at the end of the statement.
Implementation code:
1. Aspect.h
#ifndef ____aspect_h____
#define ____ASPECT_H____
template <class t>
class Baseaspect
{
T * M_PT;
Protected:
Baseaspect (t* PT)
: M_pt (PT)
{
}
virtual ~baseaspect ()
{
} public
:
t* operator-> ()
{return
m_pt;
}
};
Template <class t>
class Logaspect:public baseaspect<t>
{
const char* m_name;
Public:
Logaspect (t* pt, const char* name = "")
: Baseaspect<t> (PT)
, M_name (name)
{
std::cout<< "Logaspect:" <<m_name<< "Begin" <<std::endl;
}
~logaspect ()
{
std::cout<< "logaspect:" <<m_name<< "End" <<std::endl;
}
};
Template <class t>
class Lockaspect:public baseaspect<t>
{public
:
LockAspect (t* PT)
: Baseaspect<t> (PT)
{
std::cout<< "Lockaspect:lock" <<std::endl ;
}
~lockaspect ()
{
std::cout<< "Lockaspect:unlock" <<std::endl;
}
};
#endif//____aspect_h____
2.main.cpp
#include <iostream>
using namespace std;
#include "Aspect.h"
class Action
{public
:
void Say (const char* str)
{
std::cout<< Action::say ("<<str<<") "<<std::endl;
}
};
int main (int argc, char* argv[])
{
Action A;
Logaspect<action> (&a, "Action::say")->say ("Hi");
std::cout<<std::endl;
Lockaspect<action> (&a)->say ("Hello");
while (1);
return 0;
}
Execution Results: