Original: http://blog.csdn.net/zhangerqing/article/details/8239539
Decoration mode is to add some new functions to an object, and is dynamic, require decorative objects and decorated objects to implement the same interface, decorative objects hold the object of the decoration objects, the diagram is as follows:
The source class is a decorated class, and the decorator class is a decorative class that can dynamically add some functionality to the source class, with the following code:[Java]View plain copy public interface sourceable {public void method (); }[Java]View plain copy public class Source implements sourceable {@Override public void method () {Sys Tem.out.println ("The original method!"); } }[Java] View Plain copy public class decorator implements sourceable { private Sourceable source; public decorator (sourceable source) { super (); this.source = source; } @ override public void method () { system.out.println ("before decorator!"); source.method (); system.out.println ("after decorator!"); } }
Test class: [Java] view plain copy public class Decoratortest {public static void main (string[] args) { sourceable Source = new Source (); sourceable obj = new Decorator (source); Obj.method (); } }
Output:
Before decorator!
The original method!
After decorator!
Application Scenarios for Adorner mode:
1, need to extend the functionality of a class.
2, dynamic for an object to add functionality, but also can be dynamically revoked. (Inheritance cannot do this, the inherited functionality is static and cannot be dynamically deleted.) )
Cons: Produce too many similar objects, not easy to debug.