Decorator Pattern 装饰者模式

When I inherit behavior by subclassing, that behavior is set statically at compile time. In addition, all subclasses must inherit the same behavior. If however, I can extend an object's behavior through composition, then I can do this dynamically at runtime. It is possible for me to add multiple new responsibilities to objects through this technique, including responsibilities that were not even thought of by the designer of the superclass. And, I don't have to touch their code! By dynamically composing objects, I can add new functionality by writing new code rather than altering existing code. Bcause I'm not changing existing code, the chances of introducing bugs or causing unintended side effects in pre-existing code are much reduced.


Design Principle:

Classes should be open for extension, but closed for modification.

Classes are easy to extend to incorporate new behavior without modifying existing code.


Decorator Pattern: attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

装饰者模式在原有的Concrete Component基础上,利用Decorator包装上新的行为。


以饮料为例子:

Beverage是父抽象类(也可为接口),CondimentDecorator是继承Beverage的抽象类(也可为接口)。

public abstract class Beverage {
	String description = "Unknown Beverage";
	public String getDescription() {
		return description;
	}
	public abstract double cost();
}

public abstract class CondimentDecorator extends Beverage{
	@Override
	public abstract String getDescription();
}

Concrete Beverage和Concrete Decorator:

public class Espresso extends Beverage{
	public Espresso() {
		description = "Espresso";
	}
	
	@Override
	public double cost() {
		return 1.99;
	}
}

public class Mocha extends CondimentDecorator{
	Beverage beverage;
	public Mocha(Beverage beverage) {
		this.beverage = beverage;
	}
	
	@Override
	public String getDescription() {
		return beverage.getDescription() + ", Mocha";
	}
	
	@Override
	public double cost() {
		return 1.20+beverage.cost();
	}
}
Runtime Test:

public class TestMain {
	public static void main(String[] args) {
		Beverage beverage = new Espresso();
		beverage = new Mocha(beverage);
		System.out.println(beverage.getDescription() + ", cost " + beverage.cost());
	}
}

装饰者模式:

Decorator和Component继承与同一个超类,类型一样。Decorator实际上是个Wrapper。以超类为引用,以Concrete Component为内核,用Decorator进行包装。Decorator内含有对于前一层Component的引用,所以能在其Component方法的基础上进行修改。Java 的IO就是这样chain起来的。

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

  1. 需要扩展一个类的功能,或给一个类增加附加责任。
  2. 需要动态地给一个对象增加功能,这些功能可以再动态地撤销。
  3. 需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变得不现实。

应用:咖啡添加调味剂,Java IO API.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值