装饰模式是对对象功能的扩展的一种模式,好处在于不更改原有对象的特性,只是通过注入方式为对象添加一些额外的功能,使得对象的功能丰富,特别有利于对对象行为的多个细小行为的添加。装饰模式是一种结构型模式。
装饰模式类图:
[img]http://dl.iteye.com/upload/attachment/364545/b30e222f-1f5e-3ad1-a21f-ff3cec6723b6.jpg[/img]
具体demo示例:
//组件抽象类
具体实现:
装饰者:
具体装饰者1:
具体装饰者2:
测试类:
说明:和直接子类相比,利用装饰者的话,能够更灵活的丰富对象的行为。
装饰模式类图:
[img]http://dl.iteye.com/upload/attachment/364545/b30e222f-1f5e-3ad1-a21f-ff3cec6723b6.jpg[/img]
具体demo示例:
//组件抽象类
package decoratorPattern;
public abstract class Component {
public abstract void doSomething();
}
具体实现:
package decoratorPattern;
public class ConcreteComponent extends Component{
@Override
public 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;
}
}
具体装饰者1:
package decoratorPattern;
public class ConcreteDecoratorA extends Decorator {
@Override
public void doSomeDecoratorThing() {
System.out.println("Morning,");
}
}
具体装饰者2:
package decoratorPattern;
public class ConcreteDecoratorB extends Decorator{
@Override
public 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();
}
}
说明:和直接子类相比,利用装饰者的话,能够更灵活的丰富对象的行为。