image.png

咖啡馆订单系统

需求

image.png

差的方案

调料增加,就会产生变动,搭配就会重新配置,类爆炸
image.png

好一点方案

不会产生类爆炸,但是新的调料产生,影响原有代码,维护性差,
调料改为两份,不是Boolean,就会变化
image.png

装饰者模式原理

概念

image.png
image.png

重新设计方案

image.png

image.png

具体实现代码

image.png

0.Drink一级父类

image.png

1.coffee 父类

image.png

2.不同coffee子类

image.png

3.decorator 父类

image.png

4.decorator 子类 不同调料

image.png

5.咖啡馆 测试类

image.png

装饰者模式关键点

传统方式,复杂度乘方
超类封装调料,缺点需要修改代码
装饰者模式在运行中,添加类的功能;
面向对象在编译期,添加类的属性

IO类,使用装饰者模式

image.png

1.子类

public class UpperCaseInputStream extends FilterInputStream {
protected UpperCaseInputStream(InputStream in) {
super(in);
}

  1. **public int **read() **throws **IOException {<br /> **int **c = **super**.read();<br /> **return **c == -1 ? c : Character.toUpperCase((**char**)c);<br /> }
  2. **public int **read(**byte**[] b, **int **offset, **int **len) **throws **IOException {<br /> **int **result = **super**.read(b, offset, len);
  3. **for**(**int **i = 0; i < result; ++i) {<br /> b[i] = (**byte**)Character.toUpperCase((**char**)b[i]);<br /> }
  4. **return **result;<br /> }<br />}

2.main 方法

public class InputTest {
public InputTest() {
}

  1. **public static void **main(String[] args) {<br /> **try **{<br /> UpperCaseInputStream in = **new **UpperCaseInputStream(**new **BufferedInputStream(**new **FileInputStream(**"F:\\test.txt"**)));
  2. **int **c;<br /> **while**((c = in.read()) >= 0) {<br /> System.out.print((**char**)c);<br /> }<br /> } **catch **(IOException var3) {<br /> var3.printStackTrace();<br /> }
  3. }<br />}

开放-关闭原则