First, seeDecorator mode definition:Dynamically attaches the responsibility to the object. If you want to expand your capabilities, the decorations provide more flexible alternatives than inheritance!
Let's take a look at the class diagram given in "big talk Design Patterns:
Actually,Decoration ModeThat is, the modifier object is treated as a "wrapper". In other words, the object to be decorated is passed as a parameter to the decoration object and then operated. (If you do not understand it, you want to correct it.) the following code is used to understand the class diagram:
This is the common interface between the decorator and the specific objects to be decorated:
public abstract class Component { abstract void Operation();}Object
Public class ConcreteComponment extends Component {@ Override void Operation () {System. out. println ("actions on specific objects ");}}Decorated with base classes
public class Decorator extends Component { private Component component; public void setComponent(Component component) { this.component = component; } @Override void Operation() { if (component!=null){ component.Operation(); } }}Decorator
Public class ConcreateDecoratorA extends Decorator {private String addState; @ Override void Operation () {super. operation (); addState = "New state"; System. out. println ("ConcreateDecoratorA operations ");}}Decorator B
Public class ConcreateDecoratorB extends Decorator {@ Override void Operation () {AddedBehavior (); super. Operation ();/**
The decorator Can add his/her own behavior before and after the behavior of the entrusted decorator to achieve a specific purpose.
**/System. out. println ("ConcreateDecoratorB operation");} public void AddedBehavior () {System. out. println ("AddedBehavior ");}}Test class:public class Main { public static void main(String[] args){ConcreteComponment con=new ConcreteComponment(); ConcreateDecoratorA a=new ConcreateDecoratorA(); a.setComponent(con); a.Operation(); ConcreateDecoratorB b=new ConcreateDecoratorB(); b.setComponent(con); b.Operation(); }}
Test results:
Operation of a specific object ConcreateDecoratorA operation of AddedBehavior operations of a specific object ConcreateDecoratorB