0%

装饰者模式

装饰者模式

星巴克咖啡订单项目

咖啡种类/单品咖啡:Espresso(意大利浓咖啡)、ShortBlack、LongBlack(美式 咖啡)、Decaf(无因咖啡)

调料:Milk、Soy(豆浆)、Chocolate

要求在扩展新的咖啡种类时,具有良好的扩展性、改动方便、维护方便

使用OO的来计算不同种类咖啡的费用: 客户可以点单品咖啡,也可以单品咖 啡+调料组合。

装饰者模式定义

装饰者模式:动态的将新功能附加到对象上。在对象功能扩展方面,它比继承更 有弹性,装饰者模式也体现了开闭原则(ocp)

装饰者模式原理

  • 装饰者模式就像打包一个快递

    • 主体:比如:陶瓷、衣服 (Component) // 被装饰者
    • 包装:比如:报纸填充、塑料泡沫、纸板、木板(Decorator)
  • Component 主体:比如类似前面的Drink

  • ConcreteComponent和Decorator

    ConcreteComponent:具体的主体, 比如前面的各个单品咖啡 Decorator: 装饰者,比如各调料.

  • 在如Component与ConcreteComponent之间,如果 ConcreteComponent类很多,还可以设计一个缓冲层,将共有的部分提取出来, 抽象成一个类。

装饰者模式解决星巴克咖啡订单

notes

注:感觉Drink指向Decorator那边箭头指反了。

装饰者模式下的订单:2份巧克力+一份牛奶的Espresso

1
2
3
4
5
6
7
8
9
10
11
// 1. 点一份 Espresso
Drink order = new Espresso();

// 2. order 加入一份牛奶
order = new Milk(order);

// 3. order 加入一份巧克力
order = new Chocolate(order);

// 4. order 再加入一份巧克力
order = new Chocolate(order);

装饰者模式在JDK应用的源码分析

notes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package Decorator;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class IO {
public static void main(String[] args) throws IOException {
//说明
//1. InputStream是抽象类。类似我们前面讲的Drink
//2. FileInputStream是InputStream 子类,类似我们前面的DeCaf, LongBlack
//3. FilterInputStream是InputStream 子类:类似我们前面的Decorator 修饰者
//4. DataInputStream是FilterInputStream 子类,具体的修饰者,类似前面的Milk, Soy等
//5. FilterInputStream类有protected volatile InputStream in;即含被装饰者
//6.分析得出在jdk的io体系中,就是使用装饰者模式
DataInputStream dis = new DataInputStream(new FileInputStream("d:\\abc.txt"));
System.out.println(dis.read());
dis.close();
}
}
-------------本文结束感谢您的阅读-------------