Decoration mode is used to add properties dynamically and flexibly to an object, consisting mainly of the following roles:
- Component: defines an object interface that can dynamically add responsibilities to these objects, in this case the product
- Concretecomponent: The specific object to be added, in this case the Productimpl, the attribute is added by AddAttribute
- Decorator: The abstraction of the adorner, maintaining a component pointer, and inheriting the pointer; In this case, the Basechange
- Concretecomponent: Specific adorners, in this case Onechange and Twochange
The code is as follows:
Public Interface Product { publicvoid AddAttribute ();}
Public class Implements Product { @Override publicvoid AddAttribute () { System.out.println ("Add base Attribute");} }
Public class Implements Product { private product product; Public Basechange (product product) { this. Product= product; } @Override publicvoid AddAttribute () { product.addattribute (); }}
public class onechange extends Basechange { public Span style= "color: #000000;" > Onechange (product product) { super (pro Duct); } @Override public void AddAttribute () { super .addattribute () ; SYSTEM.OUT.PRINTLN ( one change ); }}
Public class extends Basechange { public twochange (product product) { Super(product); } @Override Public void AddAttribute () { super. AddAttribute (); System.out.println ("Change");} }
Public class App { publicstaticvoid main (string[] args) { new Productimpl (); New Twochange (new onechange (product)); Change.addattribute (); }}
The output is:
ADD Base Attributeone changetwo Change
Design mode (decorative mode)