菜鸟硕枫设计模式系列之10 装饰模式
装饰模式是对对象功能的扩展的一种模式,好处在于不更改原有对象的特性,只是通过注入方式为对象添加一些额外的功能,使得对象的功能丰富,特别有利于对对象行为的多个细小行为的添加。装饰模式是一种结构型模式。
装饰模式类图:
具体demo示例:
//组件抽象类
package decoratorPattern;public abstract class Component {public abstract void doSomething();}
package decoratorPattern;public class ConcreteComponent extends Component{@Overridepublic void doSomething() {System.out.println("welcome to Taobao.");}}
package decoratorPattern;public abstract class Decorator extends Component{private Component component;public abstract void doSomeDecoratorThing();public void doSomething(){doSomeDecoratorThing();component.doSomething();}public void setComponent(Component component) {this.component = component;}}
package decoratorPattern;public class ConcreteDecoratorA extends Decorator {@Overridepublic void doSomeDecoratorThing() {System.out.println("Morning,");}}
package decoratorPattern;public class ConcreteDecoratorB extends Decorator{@Overridepublic void doSomeDecoratorThing() {System.out.println("Afternoon,");}}
package decoratorPattern;public class decoratorPatternTest {public static void main(String[]args){Component component = new ConcreteComponent();System.out.println("-----------------------------");component.doSomething();System.out.println("-----------------------------");ConcreteDecoratorA concreteDecoratorA =new ConcreteDecoratorA();concreteDecoratorA.setComponent(component);concreteDecoratorA.doSomething();System.out.println("-----------------------------");ConcreteDecoratorB concreteDecoratorB =new ConcreteDecoratorB();concreteDecoratorB.setComponent(component);concreteDecoratorB.doSomething();}}