装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构
这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
Class Diagram
Implementation
类接口
1 2 3 4 5 6 7 8 9
| public abstract class Beverage { public String description = "Unknown Beverage";
public String getDescription() { return description; }
public abstract double cost(); }
|
实体类(被装饰者)
1 2 3 4 5 6 7 8 9 10 11
| public class DarkRoast extends Beverage {
public DarkRoast() { description = "DarkRoast"; }
@Override public double cost() { return 0.99; } }
|
抽象装饰者
1 2 3 4 5 6 7 8
| public abstract class CondimentDecorator extends Beverage {
public abstract String getDescription();
}
|
具体装饰者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| 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 0.20 + beverage.cost(); } }
|
测试类
1 2 3 4 5 6 7 8 9 10 11
| public class DecoratorTest {
@Test public void test() throws Exception{ Beverage beverage1 = new DarkRoast(); beverage1 = new Mocha(beverage1); beverage1 = new Mocha(beverage1); System.out.println(beverage1.getDescription()+ " $" + beverage1.cost()); }
}
|
Example
- java.io.BufferedInputStream(InputStream)
- java.io.BufferedOutputStream(OutputStream)
Refence