1 Decoration Mode2 Overview3 add some extra responsibilities to an object dynamically. For added functionality, the decorator mode is more flexible than generating subclasses. 4 5 6 Applicability71add responsibilities to a single object in a dynamic, transparent manner without affecting other objects. 8 92. Handle the duties that can be undone. Ten One3When you cannot expand by using methods that generate subclasses. A participants -1. Component - defines an object interface that can dynamically add responsibilities to these objects. the -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. + A4. Concretedecorator atAdd responsibilities to the component.
Test class:
1 Public classTest {2 3 Public Static voidMain (string[] args) {4Man mans =NewMan ();5Mandecoratora MD1 =NewMandecoratora ();6Mandecoratorb MD2 =NewMandecoratorb ();7 8 Md1.setperson (man);9 Md2.setperson (MD1);Ten md2.eat (); One } A}
1 public interface person { 2 3 Eat (); 4 }
1 Public class Implements Person {23 Public void eat () {4 System.out.println ("Men are eating"); 5 }6 }
1 Public Abstract classDecoratorImplementsPerson {2 3 protectedperson person ;4 5 Public voidSetperson (person person) {6 This. person =Person ;7 }8 9 Public voideat () {Ten person.eat (); One } A}
1 Public classMandecoratoraextendsDecorator {2 3 Public voideat () {4 Super. Eat ();5 reeat ();6System.out.println ("Mandecoratora class");7 }8 9 Public voidreeat () {TenSystem.out.println ("Eat Another Meal"); One } A}
1 Public class extends Decorator {2 3 Public void eat () {4 Super . Eat (); 5 System.out.println ("==============="); 6 System.out.println ("Mandecoratorb class"); 7 }8 }
Use Daniel's code to take notes, learn to observe the continuous progress ... With so many frameworks, the source code is still not easy to understand AH
Java design pattern--structural mode--Decorative mode