JAVA design pattern-Decorator)
I. Overview
Dynamically add some additional responsibilities to an object. The Decorator mode is more flexible than the subclass generation function.
Ii. Applicability
1. Add roles to a single object dynamically and transparently without affecting other objects.
2. Handle the responsibilities that can be undone.
3. When the subclass generation method cannot be used for expansion.
3. Participants
1. Component defines an object interface that can dynamically add responsibilities to these objects.
2. ConcreteComponent defines an object and can add some responsibilities to this object.
3. Decorator maintains a pointer to the Component object and defines an interface consistent with the Component interface.
4. ConcreteDecorator adds responsibilities to components.
Iv. Category chart
V. Example
Component
Package com. lyz. design. decorator;/*** defines the Component interface Person * @ author liuyazhuang **/public interface Person {void eat ();}
ConcreteComponent
Package com. lyz. design. decorator;/*** Person interface implementation class Man * @ author liuyazhuang **/public class Man implements Person {public void eat () {System. out. println (Men eating );}}
Decorator
Package com. lyz. design. decorator;/*** Decorator abstract class implements the Person interface * @ author liuyazhuang **/public abstract class Decorator implements Person {protected Person person; public void setPerson (Person person Person) {this. person = person;} public void eat () {person. eat ();}}
ConcreteDecorator
Package com. lyz. design. decorator;/*** Decorator subclass * @ author liuyazhuang **/public class ManDecoratorA extends Decorator {public void eat () {super. eat (); reEat (); System. out. println (ManDecoratorA class);} public void reEat () {System. out. println (another meal );}}
Package com. lyz. design. decorator;/*** Decorator subclass * @ author liuyazhuang **/public class ManDecoratorB extends Decorator {public void eat () {super. eat (); System. out. println (====================); System. out. println (ManDecoratorB class );}}
Test
Package com. lyz. design. decorator;/*** Test class * @ author liuyazhuang **/public class Test {public static void main (String [] args) {Man man = new Man (); manDecoratorA md1 = new ManDecoratorA (); ManDecoratorB md2 = new ManDecoratorB (); md1.setPerson (man); md2.setPerson (md1); md2.eat ();}}
Result
ManDecoratorA class ========================== ManDecoratorB class