Overview:
Add some extra responsibilities to an object dynamically. For added functionality, the decorator mode is more flexible than generating subclasses.
Type: Structural mode.
Class Diagram:
Applicability:
1. Add responsibilities to a single object in a dynamic, transparent manner without affecting other objects.
2. Handle the duties that can be undone.
3. When a method of generating subclasses cannot be used for expansion.
Participants:
1.Component
Defines an object interface that can dynamically add responsibilities to these objects.
2.ConcreteComponent
Defines an object that can add some responsibility to the object.
3.Decorator
Maintains a pointer to the component object and defines an interface that is consistent with the component interface.
4.ConcreteDecorator
Add responsibilities to the component.
Example:
ComponentPublicInterfaceperson {void eat ();} ConcretecomponentPublicClassMansImplementsperson {PublicvoidEat () {System.out.println ("The man is Eating"); }}decoratorPublicAbstractClassDecoratorImplementsperson {protected person person;PublicvoidSetperson (person person) {This.person = person; }PublicvoidEat () {person.eat ();}} ConcretedecoratorPublicClassMandecoratoraExtendsDecorator {PublicvoidEat () {Super.eat (); Reeat (); System.out.println ("Mandecoratora class"); }PublicvoidReeat () {System.out.println ("Eat another Meal"); }}PublicClassMandecoratorbextends decorator {public void eat () {super.eat (); System.out.println ( "==============="); System.out.println ( "Mandecoratorb class");}} Test public class test {public static void main (string[] args) {man mans = new Man (); Mandecoratora md1 = new Mandecoratora (); Mandecoratorb MD2 = new Mandecoratorb (); Md1.setperson (man); Md2.setperson (MD1); Md2.eat () ; }}
Result
男人在吃再吃一顿饭ManDecoratorA类===============ManDecoratorB类
23 Design Modes (20): Decorative mode