pass an object as a parameter and then wrap the object --- change the method or add some new behavior --- the decorative design pattern --- Decorator mode ---decorate model
Change a method:
1. by inheriting this class, and then overriding the method
2. create decorative objects by passing objects, and re-provide the corresponding methods in the decoration class
Disadvantages of Inheritance:
1. Single Inheritance
2. create a parent class object using the up shape, you can call the overridden method in the subclass, cannot use the original method in the parent class
3. if the parent object already exists, you cannot use the overridden method in the subclass
Disadvantages of decorative Design patterns:
may increase the redundancy of the code --- proxy mode
1 //Man's interface2 Public InterfacePerson {3 4 voideat ();5 6 voidsleep ();7 8 }9 Ten One //Star of the realization class A Public classStarImplementsPerson { - -@SuppressWarnings ("Unused") the PrivatePerson p; - - PublicStar (person p) { - This. P =p; + } - + @Override A Public voideat () { atSystem.out.println ("The Star eats the wild vegetables ~ ~ ~"); - } - - @Override - Public voidsleep () { -System.out.println ("Bed count stars ~ ~ ~"); in } - to } + - //Worker Realization Class the Public classWorkerImplementsPerson { * $ @OverridePanax Notoginseng Public voideat () { -SYSTEM.OUT.PRINTLN ("The workers eat a good meal ~ ~ ~ and then eat one months of soil ~ ~ ~"); the } + A @Override the Public voidsleep () { +System.out.println ("Bed count stars ~ ~ ~"); - } $ $ } - - //packaging workers into stars, but essentially workers or workers the Public classPersondemo { - Wuyi Public Static voidMain (string[] args) { the -Worker p =NewWorker (); Wu - p.eat (); About $Star s =NewStar (p); - - s.eat (); - A p.eat (); + the } - $}
Java Decorative design pattern