First, inheritance
Use scenarios: You can use inheritance when you can control the construction of this class.
Advantages: Simple and easy to use,
Disadvantage: The coupling is greatly enhanced, not conducive to the maintenance of the later, so for the inheritance of this method, use with caution.
Code implementation:
Second, decorator mode
Usage scenarios: 1, wrapper objects and packaged objects implement the same interface
2, packaging objects need to get to the wrapped object reference.
Disadvantage: If the interface method is more, enhance one of the methods, other functions of the method needs the original call;
Code implementation:
/**
* Decorator Mode:
* Enhance the GetParameter method of the request so that it is encoded in the format Utf-8
*/
public class Myservletrequest extends httpservletrequestwrapper{
private HttpServletRequest request;
Public myservletrequest (HttpServletRequest request) {
Super (Request);
This.request=request;
}
@Override//Override GetParameter method
public string GetParameter (string name) {
String value = request.getparameter (name);
try {
Value=new String (value.getbytes ("iso-8859-1"), "Utf-8");
} catch (Unsupportedencodingexception e) {
throw new RuntimeException (e);
}
return value;
}
Third, dynamic agent
Usage Scenario: An enhanced object must implement an interface.
Requirements: (1) define a waiter interface
Waiter
Public interface Waiter {
Service
public void serve ();
}
(2) A waiter's class and implement the attendant interface. The waiter has a way of serving.
public class Manwaiter implements waiter {
public void serve () {
System.out.println ("in service ...");
}
}
Now you want the waiter to be polite when serving, and to use polite language before and after the service.
Dynamic Proxy Implementation code:
public class Demo {
@Test
public void Fun1 () {
Waiter Manwaiter = new Manwaiter ();//target object
/*
* Give three parameters to create a method to get the proxy object
*/
ClassLoader loader = This.getclass (). getClassLoader ();
Class[] interfaces = {Waiter.class};
Invocationhandler h = new Waiterinvocationhandler (manwaiter);//Parameter manwaiter indicates target object
To get the proxy object, the proxy object is an object that is enhanced on the basis of the target object!
Waiter Waiterproxy = (waiter) proxy.newproxyinstance (loader, interfaces, h); Gets the Manwaiter enhanced object
Waiterproxy.serve (); Execute the Invoke method in Waiterinvocationhandler here
}
}
Define a class implementation Invocationhandler this is the enhanced class
public class Waiterinvocationhandler implements Invocationhandler {
Private Waiter waiter;//target object
Public Waiterinvocationhandler (Waiter waiter) {
This.waiter = Waiter;
}
public object invoke (object proxy, Method method, object[] args)
Throws Throwable {
SYSTEM.OUT.PRINTLN ("Hello! ");
This.waiter.serve ();//Call target method of target object
System.out.println ("Good-bye!" ");
return null;
}
}
A few methods of "enhanced" class in Java.