Inherited
Fixed by the object being enhanced
The enhanced content is also fixed
Decorator mode
Objects that are enhanced can be toggled.
Enhanced content is fixed
There is also a more flexible approach to aspect-oriented programming (AOP), which is more flexible than decorator mode, with enhanced objects and enhanced content that can be replaced.
Package Cn.ph.proxy;import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;import java.lang.reflect.proxy;//using proxy mode public class MyCar {public static void main (string[] args) {//Object java.lang.re Flect. Proxy.newproxyinstance//(ClassLoader loader, class<?>[] interfaces, Invocationhandler h) throws Illegalargument Exception//Parameter type/** * param1: tells the virtual machine which bytecode loader to load the corresponding bytecode file, fixed value * param2: Tell the virtual machine what bytecode is being created * PARAM3: Tell the virtual machine to be How the individual methods of the created bytecode file are processed * The corresponding proxy file is generated after compilation Mycar$1.class */Car car = (car) proxy.newproxyinstance (MyCar.class.getCl Assloader (), GoogleCar.class.getInterfaces (), new Invocationhandler () {@Override public object invoke (object proxy, Method method, object[] args) throws Throwable {//code executed in each method if ("Start". Equals (Method.getname ())) {//Method.getname (). Equalsignorecase ("Start")//Ignore case System.out.println (Method.getName ());//Enhanced Start Method} Method.invoke (New Googlecar ()); return null; } }); Car.start ();//execute the above Invoke method Car.run (); Car.stop ();}} Reference decorator Mode class Testcar implements car {private car car;public testcar (car car) {This.car = car;} @Overridepublic void Run () {Car.run ();} @Overridepublic void Start () {System.out.println ("view Weather"); System.out.println ("Check the Road"); Car.start ();} @Overridepublic void Stop () {car.stop ();}} Class Googlecar implements car {@Overridepublic void start () {System.out.println ("car started Up");} @Overridepublic void Run () {System.out.println ("car Ran");} @Override public void Stop () {System.out.println ("car Stopped"); }}interface Car {void start (); void run (); void stop ();}
Dynamic agent, adornment mode, and inheritance simple implementation in Java