define
Dynamically assign additional responsibilities to an object. Decorator patterns are more flexible than subclassing in terms of adding functionality.
nature
Dynamic combination, dynamic is the means, combination is the end.
His role
-
Component
The core role in adding functionality, the interface to component objects, can add functionality dynamically to those objects.
-
ConcreteComponent
Implement component interfaces. Concrete component objects, usually primitive objects decorated with decorators, can be assigned responsibilities.
-
Decorator (Decorator)
An abstract parent of all decorators that implements the same interface as Component and holds an object to be decorated.
-
ConcreteDecorator
The actual decorator object implements the functionality added to the decorator object.
The sample code
Public abstract class Person {public abstract void dressed(); } public class Boy extends Person{@override public void dressed() {system.out.print (" wearing a shirt "); }} /** * public abstract class extends Person{private Person; public PersonCloth(Person person) { this.person = person; } @Override public void dressed() { person.dressed(); Public class ExpensiveCloth extends PersonCloth{public class ExpensiveCloth(Person Person) {public class ExpensiveCloth extends PersonCloth{public class ExpensiveCloth(Person Person) { super(person); } private void dressShirt(){system.out.println (" dressShirt "); } private void dressLeather(){system.out.println (" dressLeather "); } @Override public void dressed() { super.dressed(); dressShirt(); dressLeather(); Public class CheapCloth extends PersonCloth{public class CheapCloth(Person) {super(Person); } / / private void shorts (){system.out.println (" shorts "); } @Override public void dressed() { super.dressed(); dressShorts(); }}Copy the code
The results
Put on expensive clothes wear shirts wear short sleeves wear leather ============= put on cheap clothes wear shirts wear short sleevesCopy the code
function
Adding functionality to an object dynamically, and from outside the object, changes the object’s appearance.
advantages
- More flexible than inheritance.
- Easier to reuse functionality.
- Simplify high-level definitions by adding as much functionality to an object as you want by combining decorators. Because in high-level definition, you can not define all functions, but only the most basic can be defined.
disadvantages
- Many fine-grained objects are produced.
When to use
- If you need to add functionality to an object in a dynamic and transparent manner without affecting other objects, you can use the decorator pattern.
- If subclasses are not appropriate for extension, consider using the decorator pattern, because the decorator pattern uses object composition, in which decorator objects hold references to decorator objects.