Add the AOP feature for your J2EE application in the gof modifier Mode

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.