This essay mainly introduces the implementation of a simple decorator design pattern using Java:
Let’s first look at the class diagram of the decorator design pattern:
As can be seen from the figure, we can decorate any implementation class of the Component interface, and these implementation classes also include the decorator itself, which can also be decorated again.
Below is a simple decorator design pattern implemented in Java. It provides a decorator system that starts with the basic addition of coffee and can continue to add milk, chocolate, and sugar.
interface Component { void method();}class Coffee implements Component { @Override public void method() { // TODO Auto-generated method stub System.out.println("Pour in coffee"); } }class Decorator implements Component { public Component comp; public Decorator(Component comp) { this.comp = comp; } @Override public void method() { // TODO Auto-generated method stub comp.method(); } }class ConcreteDecorateA extends Decorator { public Component comp; public ConcreteDecorateA(Component comp) { super(comp); this.comp = comp; } public void method1() { System.out.println("Pour in milk"); } public void method2() { System.out.println("Add sugar"); } public void method() { super.method(); method1(); method2(); }}class ConcreteDecorateB extends Decorator { public Component comp; public ConcreteDecorateB(Component comp) { super(comp); this.comp = comp; } public void method1() { System.out.println("Add chocolate"); } public void method() { super.method(); method1(); }}public class TestDecoratePattern { public static void main(String[] args) { Component comp = new Coffee(); comp.method(); System.out.println("--------------------------------------------------"); Component comp1 = new ConcreteDecorateA(comp); comp1.method(); System.out.println("--------------------------------------------------"); Component comp2 = new ConcreteDecorateB(comp1); comp2.method(); System.out.println("--------------------------------------------------"); Component comp3 = new ConcreteDecorateB(new ConcreteDecorateA(new Coffee())); comp3.method(); System.out.println("--------------------------------------------------"); Component comp4 = new ConcreteDecorateA(new ConcreteDecorateB(new Coffee())); comp4.method(); }} Running results:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.