装饰(Decorator)模式

装饰(Decorator)模式又名包装(Wrapper)模式。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。

一,结构

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。

具体构件(Concrete Component)角色:定义一个将要接收附加责任的类。

装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。

具体装饰(Concrete Decorator)角色:负责给构件对象"贴上"附加的责任。

二,示例代码

/**
 * 抽象构件
 * @author Salmon
 *
 */
public interface Component {
	public void operation();
}

/**
 * 具体构件
 * @author Salmon
 *
 */
public class ConcreteComponent implements Component {
	public void operation() {
		System.out.println("ConcreteComponent.Operation()");
	}
}

/**
 * 装饰(即组合又继承)
 * @author Salmon
 *
 */
public class Decorator implements Component {
	protected Component component;

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

	public void operation() {
		if (component != null)
			component.operation();
	}
}

/**
 * 具体装饰
 * @author Salmon
 *
 */
public class ConcreteDecoratorA extends Decorator {
	private String addedState;

	public void operation() {
		super.operation();
		addedState = "new state";
		System.out.println("ConcreteDecoratorA.Operation()");
	}
}

/**
 * 具体装饰
 * @author Salmon
 *
 */
public class ConcreteDecoratorB extends Decorator {
	public void operation() {
		super.operation();
		AddedBehavior();
		System.out.println("ConcreteDecoratorB.Operation()");
	}

	private void AddedBehavior() {
		System.out.println("new state");
	}
}

/**
 * 客户代码
 * @author Salmon
 *
 */
public class Client {
	public static void main(String[] args) {
		ConcreteComponent c = new ConcreteComponent();
		ConcreteDecoratorA d1 = new ConcreteDecoratorA();
		ConcreteDecoratorB d2 = new ConcreteDecoratorB();
		d1.setComponent(c);
		d2.setComponent(d1);
		d2.operation();
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值