You do not need to modify the existing Code Or its interface, the application of Gang of Four (gof) decorator mode provides a way to add AOP.
Suppose we have a simple interface:
Public interface imybusinessobject {
Public String doexecute (string in );
}
The following is the implementation class of this interface.
Public class mybusinessobject implements imybusinessobject {
Public String doexecute (string in ){
System. Out. println ("here in mybusinessobject doexecute: input:" + in );
Return in;
}
}
Now we need to add some actions before and after executing the doexecute method. The decorator mode can help us implement it easily.
First define a abstract decorator class
Public abstract class adecorator implements imybusinessobject {
Protected imybusinessobject target;
Public void settarget (imybusinessobject target _){
This.tar get = target _;
}
Public adecorator (){}
Public adecorator (imybusinessobject target _){
Settarget (target _);
}
}
Now we define a debugconcretedecorator extension adecorator to add the debug information before and after calling the doexecute method.
Public class debugconcretedecorator extends adecorator {
Public String doexecute (string in ){
System. Out. println ("debugconcretedecorator: Before method: doexecute ");
String ret = target. doexecute (in );
System. Out. println ("debugconcretedecorator: After method: doexecute ");
Return ret;
}
}
The following code can be used for calling.
Imybusinessobject aimybusinessobject = new mybusinessobject ();
Imybusinessobject wrappedobject =
New debugconcretedecorator (aimybusinessobject );
Wrappedobject. doexecute ("Hello World ");
The output is as follows:
Debugconcretedecorator: Before method: doexecute
Here in mybusinessobject doexecute: input: Hello World
Debugconcretedecorator: After method: doexecute