This essay mainly introduces the implementation of a simple decorator design pattern in Java:
First look at the class diagram of the adorner design pattern:
As you can see, we can decorate any implementation class of the component interface, and these implementation classes also include the adorner itself, and the adorner itself can be decorated again.
The following is a simple decorator design pattern implemented in Java, which provides the basics of adding coffee and can continue to add milk, chocolate, and sugar to the adorner system.
1 InterfaceComponent {2 voidmethod ();3 }4 classCoffeeImplementsComponent {5 6 @Override7 Public voidmethod () {8 //TODO auto-generated Method Stub9System.out.println ("Pour coffee");Ten } One A } - classDecoratorImplementsComponent { - PublicComponent comp; the PublicDecorator (Component comp) { - This. Comp =comp; - } - @Override + Public voidmethod () { - //TODO auto-generated Method Stub + Comp.method (); A } at - } - classConcretedecorateaextendsDecorator { - PublicComponent comp; - PublicConcretedecoratea (Component comp) { - Super(comp); in This. Comp =comp; - } to Public voidmethod1 () { +System.out.println ("Pour milk"); - } the Public voidmethod2 () { *System.out.println ("Add Sugar"); $ }Panax Notoginseng Public voidmethod () { - Super. Method (); the method1 (); + method2 (); A } the } + classConcretedecoratebextendsDecorator { - PublicComponent comp; $ Publicconcretedecorateb (Component comp) { $ Super(comp); - This. Comp =comp; - } the Public voidmethod1 () { -System.out.println ("Add Chocolate");Wuyi } the Public voidmethod () { - Super. Method (); Wu method1 (); - } About } $ Public classTestdecoratepattern { - Public Static voidMain (string[] args) { -Component Comp =NewCoffee (); - Comp.method (); ASystem.out.println ("--------------------------------------------------"); +Component COMP1 =NewConcretedecoratea (comp); the Comp1.method (); -System.out.println ("--------------------------------------------------"); $Component COMP2 =NewConcretedecorateb (COMP1); the Comp2.method (); theSystem.out.println ("--------------------------------------------------"); theComponent Comp3 =NewConcretedecorateb (NewConcretedecoratea (NewCoffee ())); the Comp3.method (); -System.out.println ("--------------------------------------------------"); inComponent Comp4 =NewConcretedecoratea (NewConcretedecorateb (NewCoffee ())); the Comp4.method (); the } About}
Operation Result:
The decorator design pattern allows us to freely import chocolates, milk, coffee and sugar in any order. can achieve multi-level, arbitrary order of decoration. That's a cow.
Research on the design pattern of adorners (Java implementation)