代码改变世界

设计模式之装饰模式

2011-02-10 17:08  hanwesley  阅读(243)  评论(0编辑  收藏  举报

装饰模式(Decorator):

  其目的在于

  1)不改变接口的前提下扩展功能,2)动态的给一个对象增加(扩展)其他职责。

  接口上:  Decorator is a component

  实现上: decorator has a component

package org.springframework.samples.jpetstore.dp.decorator;

/***
 * @since 2011/02/10
 * @author hanwesley CopyRight Taobao
 */
abstract class AbstractComponent {
	public abstract void sayHello();
}

class ComponentA extends AbstractComponent {
	public void sayHello() {
		System.out.print("ComponentA say Hello");
	}
}

class ComponentB extends AbstractComponent {
	public void sayHello() {
		System.out.print("ComponentB say Hello");
	}
}

abstract class Decorator extends AbstractComponent {
	private AbstractComponent component;

	public Decorator(AbstractComponent component) {
		this.component = component;
	}

	public void setComponent(AbstractComponent component) {
		this.component = component;
	}

	public void sayHello() {
		component.sayHello();
	}
}

class DecoratorA extends Decorator {
	public DecoratorA(AbstractComponent component) {
		super(component);
	}

	public void sayHello() {
		super.sayHello();
		System.out.print(" With DecoratorA");
	}
}

class DecoratorB extends Decorator {
	public DecoratorB(AbstractComponent component) {
		super(component);
	}

	public void sayHello() {
		super.sayHello();
		System.out.print(" With DecoratorB");
	}
}

// 客户端调用
public class DecoratorMain {
	public static void main(String[] args) {
		AbstractComponent componentA = new ComponentA();
		AbstractComponent decA = new DecoratorA(componentA);
		// 装饰对象实质上也是一个Component实例
		decA.sayHello();
	}
}