一、定义

动态的给一个对象添加一些额外的职责。装饰者模式提供一个弹性的继承替代方案来实现功能的扩展。

二、类图表示

装饰者模式

三、实现

1、Component

package pattern.structual.decorator;

public abstract class Component {

	public abstract void operation();
}


package pattern.structual.decorator;

public class ConcreteComponent extends Component {

	@Override
	public void operation() {
		System.out.println("ConcreteComponent operation...");
	}

}

2、Decorator

  • AbstractorDecorator
package pattern.structual.decorator;

public abstract class Decorator extends Component {

	protected Component component;
	
	public void setComponent(Component component){
		this.component = component;
	}
	
	@Override
	public void operation() {
		component.operation();
	}

}

  • ConcreteDecorator
package pattern.structual.decorator;

public class ConcreteDecoratorA extends Decorator {

	private String addedState;
	
	@Override
	public void operation() {
		super.operation();
		addedState = "new state";
		System.out.println("DecoratorA added a new state...");
	}
}


package pattern.structual.decorator;

public class ConcreteDecoratorB extends Decorator {

	@Override
	public void operation() {
		super.operation();
		this.addedBehavior();
	}
	
	public void addedBehavior(){
		System.out.println("DecoratorB addedBehavior...");
	}
}

四、使用

package pattern.structual.decorator;

public class Client {

	public static void main(String[] args) {
		Component component = new ConcreteComponent();
		
		//使用ConcreteDecoratorA装饰
		Decorator decoratorA = new ConcreteDecoratorA();
		decoratorA.setComponent(component);
		decoratorA.operation();
		
		System.out.println();
		
		//使用ConcreteDecoratorB装饰
		Decorator decoratorB = new ConcreteDecoratorB();
		decoratorB.setComponent(component);
		decoratorB.operation();
		
		System.out.println();
		
		//先使用ConcreteDecoratorA装饰,再使用ConcreteDecoratorB装饰
		decoratorB.setComponent(decoratorA);
		decoratorB.operation();
	}
}

  • 程序输出:

装饰者模式测试程序输出

五、适用场合

  • 在不影响其他对象的情况下,对某个现有对象动态的增加一个新职责或功能
  • 当不能通过增加子类实现扩展时(有两种情况:使用继承方式会造成子类膨胀或类定义被隐藏不能生成子类)