Brief introduction:
Decorator decorator, is to dynamically add some additional responsibilities to an object, the object and the adorner object needs to implement the same interface, the adorner in the method implementation of the method to invoke the target object to implement and add additional operations.
Usage scenarios:
Refine the complex functionality, scatter it into different adorners, and then dynamically combine the features as needed.
Class Diagram:
Example code:
The interface that the adorner is required to implement with the target object:
Public Interface Component { publicvoid operation ();}
The Real implementation class:
Public class Implements Component { @Override publicvoid operation () { System.out.println ( "I am doing the real thing");} }
Adorner A:
Public class Implements Component { private Component Component; Public Decoratora (Component Component) { Super(); this. Component = component; } @Override publicvoid operation () { component.operation (); System.out.println ("I am doing the extra thing A"); }
Adorner B:
Public class Implements Component { private Component Component; Public Decoratorb (Component Component) { Super(); this. Component = component; } @Override publicvoid operation () { component.operation (); System.out.println ("I am doing the extra thing B"); }
Client:
Public Static void Main (string[] args) { new decoratorb ( new Decoratora (new Concretecomponent ())); Component.operation (); }
Operation Result:
I am doing the real thing
I am doing the extra thing A
I am doing the extra thing B
Decorator mode for design mode