设计模式.md 78.3 KB
Newer Older
C
CyC2018 已提交
1 2 3
<!-- GFM-TOC -->
* [一、概述](#一概述)
* [二、创建型](#二创建型)
C
CyC2018 已提交
4 5 6 7 8 9
    * [1. 单例(Singleton)](#1-单例singleton)
    * [2. 简单工厂(Simple Factory)](#2-简单工厂simple-factory)
    * [3. 工厂方法(Factory Method)](#3-工厂方法factory-method)
    * [4. 抽象工厂(Abstract Factory)](#4-抽象工厂abstract-factory)
    * [5. 生成器(Builder)](#5-生成器builder)
    * [6. 原型模式(Prototype)](#6-原型模式prototype)
C
CyC2018 已提交
10
* [三、行为型](#三行为型)
C
CyC2018 已提交
11 12 13 14 15 16 17 18 19 20 21 22
    * [1. 责任链(Chain Of Responsibility)](#1-责任链chain-of-responsibility)
    * [2. 命令(Command)](#2-命令command)
    * [3. 解释器(Interpreter)](#3-解释器interpreter)
    * [4. 迭代器(Iterator)](#4-迭代器iterator)
    * [5. 中介者(Mediator)](#5-中介者mediator)
    * [6. 备忘录(Memento)](#6-备忘录memento)
    * [7. 观察者(Observer)](#7-观察者observer)
    * [8. 状态(State)](#8-状态state)
    * [9. 策略(Strategy)](#9-策略strategy)
    * [10. 模板方法(Template Method)](#10-模板方法template-method)
    * [11. 访问者(Visitor)](#11-访问者visitor)
    * [12. 空对象(Null)](#12-空对象null)
C
CyC2018 已提交
23
* [四、结构型](#四结构型)
C
CyC2018 已提交
24 25 26 27 28 29 30
    * [1. 适配器(Adapter)](#1-适配器adapter)
    * [2. 桥接(Bridge)](#2-桥接bridge)
    * [3. 组合(Composite)](#3-组合composite)
    * [4. 装饰(Decorator)](#4-装饰decorator)
    * [5. 外观(Facade)](#5-外观facade)
    * [6. 享元(Flyweight)](#6-享元flyweight)
    * [7. 代理(Proxy)](#7-代理proxy)
C
CyC2018 已提交
31 32 33 34 35
* [参考资料](#参考资料)
<!-- GFM-TOC -->


# 一、概述
C
CyC2018 已提交
36

C
CyC2018 已提交
37
设计模式是解决问题的方案,学习现有的设计模式可以做到经验复用。
C
CyC2018 已提交
38 39 40

拥有设计模式词汇,在沟通时就能用更少的词汇来讨论,并且不需要了解底层细节。

C
CyC2018 已提交
41 42
[源码以及 UML 图](https://github.com/CyC2018/Design-Pattern-Java)

C
CyC2018 已提交
43
# 二、创建型
C
CyC2018 已提交
44

C
CyC2018 已提交
45
## 1. 单例(Singleton)
C
CyC2018 已提交
46

C
CyC2018 已提交
47
### Intent
C
CyC2018 已提交
48

C
CyC2018 已提交
49 50
确保一个类只有一个实例,并提供该实例的全局访问点。

C
CyC2018 已提交
51
### Class Diagram
C
CyC2018 已提交
52 53 54 55 56

使用一个私有构造函数、一个私有静态变量以及一个公有静态函数来实现。

私有构造函数保证了不能通过构造函数来创建对象实例,只能通过公有静态函数返回唯一的私有静态变量。

C
CyC2018 已提交
57
<div align="center"> <img src="../pics//562f2844-d77c-40e0-887a-28a7128abd42.png"/> </div><br>
C
CyC2018 已提交
58

C
CyC2018 已提交
59
### Implementation
C
CyC2018 已提交
60

C
CyC2018 已提交
61
#### Ⅰ 懒汉式-线程不安全
C
CyC2018 已提交
62

C
CyC2018 已提交
63
以下实现中,私有静态变量 uniqueInstance 被延迟实例化,这样做的好处是,如果没有用到该类,那么就不会实例化 uniqueInstance,从而节约资源。
C
CyC2018 已提交
64

C
CyC2018 已提交
65
这个实现在多线程环境下是不安全的,如果多个线程能够同时进入 `if (uniqueInstance == null)` ,并且此时 uniqueInstance 为 null,那么会有多个线程执行 `uniqueInstance = new Singleton();` 语句,这将导致实例化多次 uniqueInstance。
C
CyC2018 已提交
66 67

```java
C
CyC2018 已提交
68
public class Singleton {
C
CyC2018 已提交
69

C
CyC2018 已提交
70
    private static Singleton uniqueInstance;
C
CyC2018 已提交
71

C
CyC2018 已提交
72 73
    private Singleton() {
    }
C
CyC2018 已提交
74

C
CyC2018 已提交
75 76 77 78 79 80
    public static Singleton getUniqueInstance() {
        if (uniqueInstance == null) {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }
C
CyC2018 已提交
81 82 83
}
```

C
CyC2018 已提交
84
#### Ⅱ 饿汉式-线程安全
C
CyC2018 已提交
85

C
CyC2018 已提交
86
线程不安全问题主要是由于 uniqueInstance 被实例化多次,采取直接实例化 uniqueInstance 的方式就不会产生线程不安全问题。
C
CyC2018 已提交
87

C
CyC2018 已提交
88
但是直接实例化的方式也丢失了延迟实例化带来的节约资源的好处。
C
CyC2018 已提交
89 90

```java
C
CyC2018 已提交
91
private static Singleton uniqueInstance = new Singleton();
C
CyC2018 已提交
92 93
```

C
CyC2018 已提交
94
#### Ⅲ 懒汉式-线程安全
C
CyC2018 已提交
95

C
CyC2018 已提交
96
只需要对 getUniqueInstance() 方法加锁,那么在一个时间点只能有一个线程能够进入该方法,从而避免了实例化多次 uniqueInstance。
C
CyC2018 已提交
97

C
CyC2018 已提交
98
但是当一个线程进入该方法之后,其它试图进入该方法的线程都必须等待,即使 uniqueInstance 已经被实例化了。这会让线程阻塞时间过程,因此该方法有性能问题,不推荐使用。
C
CyC2018 已提交
99 100

```java
C
CyC2018 已提交
101 102 103 104 105 106
public static synchronized Singleton getUniqueInstance() {
    if (uniqueInstance == null) {
        uniqueInstance = new Singleton();
    }
    return uniqueInstance;
}
C
CyC2018 已提交
107 108
```

C
CyC2018 已提交
109
#### Ⅳ 双重校验锁-线程安全
C
CyC2018 已提交
110

C
CyC2018 已提交
111
uniqueInstance 只需要被实例化一次,之后就可以直接使用了。加锁操作只需要对实例化那部分的代码进行,只有当 uniqueInstance 没有被实例化时,才需要进行加锁。
C
CyC2018 已提交
112

C
CyC2018 已提交
113
双重校验锁先判断 uniqueInstance 是否已经被实例化,如果没有被实例化,那么才对实例化语句进行加锁。
C
CyC2018 已提交
114 115

```java
C
CyC2018 已提交
116
public class Singleton {
C
CyC2018 已提交
117

C
CyC2018 已提交
118
    private volatile static Singleton uniqueInstance;
C
CyC2018 已提交
119

C
CyC2018 已提交
120 121
    private Singleton() {
    }
C
CyC2018 已提交
122

C
CyC2018 已提交
123 124 125 126 127 128 129 130 131 132
    public static Singleton getUniqueInstance() {
        if (uniqueInstance == null) {
            synchronized (Singleton.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
C
CyC2018 已提交
133 134 135
}
```

C
CyC2018 已提交
136
考虑下面的实现,也就是只使用了一个 if 语句。在 uniqueInstance == null 的情况下,如果两个线程都执行了 if 语句,那么两个线程都会进入 if 语句块内。虽然在 if 语句块内有加锁操作,但是两个线程都会执行 `uniqueInstance = new Singleton();` 这条语句,只是先后的问题,那么就会进行两次实例化。因此必须使用双重校验锁,也就是需要使用两个 if 语句。
C
CyC2018 已提交
137 138

```java
C
CyC2018 已提交
139 140 141 142
if (uniqueInstance == null) {
    synchronized (Singleton.class) {
        uniqueInstance = new Singleton();
    }
C
CyC2018 已提交
143 144 145
}
```

C
CyC2018 已提交
146
uniqueInstance 采用 volatile 关键字修饰也是很有必要的。`uniqueInstance = new Singleton();` 这段代码其实是分为三步执行。
C
CyC2018 已提交
147

C
CyC2018 已提交
148 149
1. 为 uniqueInstance 分配内存空间
2. 初始化 uniqueInstance
C
CyC2018 已提交
150
3. 将 uniqueInstance 指向分配的内存地址
C
CyC2018 已提交
151

C
CyC2018 已提交
152
但是由于 JVM 具有指令重排的特性,执行顺序有可能变成 1>3>2。指令重排在单线程环境下不会出先问题,但是在多线程环境下会导致一个线程获得还没有初始化的实例。例如,线程 T<sub>1</sub> 执行了 1 和 3,此时 T<sub>2</sub> 调用 getUniqueInstance() 后发现 uniqueInstance 不为空,因此返回 uniqueInstance,但此时 uniqueInstance 还未被初始化。
C
CyC2018 已提交
153

C
CyC2018 已提交
154
使用 volatile 可以禁止 JVM 的指令重排,保证在多线程环境下也能正常运行。
C
CyC2018 已提交
155

C
CyC2018 已提交
156
#### Ⅴ 静态内部类实现
157

C
CyC2018 已提交
158
当 Singleton 类加载时,静态内部类 SingletonHolder 没有被加载进内存。只有当调用 `getUniqueInstance()` 方法从而触发 `SingletonHolder.INSTANCE` 时 SingletonHolder 才会被加载,此时初始化 INSTANCE 实例,并且 JVM 能确保 INSTANCE 只被实例化一次。
159

C
CyC2018 已提交
160
这种方式不仅具有延迟初始化的好处,而且由 JVM 提供了对线程安全的支持。
C
CyC2018 已提交
161

C
CyC2018 已提交
162
```java
163 164 165 166 167
public class Singleton {

    private Singleton() {
    }

C
CyC2018 已提交
168 169
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
170 171 172
    }

    public static Singleton getUniqueInstance() {
C
CyC2018 已提交
173
        return SingletonHolder.INSTANCE;
174 175 176 177
    }
}
```

P
peierlong 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
#### Ⅵ 枚举实现

使用单元素的枚举类型来实现单例模式,相对于常规的单例模式,枚举实现的单例天生具有防止反射实例化对象和反序列化产生实例化对象,而且代码更加简洁,非常适合单例模式场景下使用。以下是枚举单例模式的实现。

```java

public enum EnumSingleton {
    INSTANCE;	//单元素枚举实现单例

    private String objName;

    public String getObjName() {
        return objName;
    }

    public void setObjName(String objName) {
        this.objName = objName;
    }

    public static void main(String[] args) {
        // 单例测试
        EnumSingleton firstSingleton = EnumSingleton.INSTANCE;
        firstSingleton.setObjName("firstName");
        System.out.println(firstSingleton.getObjName());

        EnumSingleton secondSingleton = EnumSingleton.INSTANCE;
        secondSingleton.setObjName("secondName");
        System.out.println(firstSingleton.getObjName());
        System.out.println(secondSingleton.getObjName());

        // 反射获取实例测试
        try {
P
peierlong 已提交
210 211 212 213
            EnumSingleton[] enumConstants = EnumSingleton.class.getEnumConstants();
            for (EnumSingleton enumConstant : enumConstants) {
                System.out.println(enumConstant.getObjName());
            }
P
peierlong 已提交
214 215 216 217
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
C
CyC2018 已提交
218
 ```
P
peierlong 已提交
219

C
CyC2018 已提交
220
该实现在多次序列化再进行反序列化之后不会得到多个实例而其它实现为了保证不会出现反序列化之后出现多个实例需要使用 transient 修饰所有字段并且实现序列化和反序列化的方法
P
peierlong 已提交
221

C
CyC2018 已提交
222
该实现可以防止反射攻击在其它实现中通过 setAccessible() 方法可以将私有构造函数的访问级别设置为 public然后调用构造函数从而实例化对象如果要防止这种攻击需要在构造函数中添加防止实例化第二个对象的代码但是该实现是由 JVM 保证只会实例化一次因此不会出现上述的反射攻击
P
peierlong 已提交
223

C
CyC2018 已提交
224
### Examples
C
crossoverJie 已提交
225

C
CyC2018 已提交
226 227 228 229
- Logger Classes
- Configuration Classes
- Accesing resources in shared mode
- Factories implemented as Singletons
C
crossoverJie 已提交
230

C
CyC2018 已提交
231
### JDK
C
crossoverJie 已提交
232

C
CyC2018 已提交
233 234 235
- [java.lang.Runtime#getRuntime()](http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#getRuntime%28%29)
- [java.awt.Desktop#getDesktop()](http://docs.oracle.com/javase/8/docs/api/java/awt/Desktop.html#getDesktop--)
- [java.lang.System#getSecurityManager()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getSecurityManager--)
C
crossoverJie 已提交
236

C
CyC2018 已提交
237
## 2. 简单工厂Simple Factory
C
CyC2018 已提交
238

C
CyC2018 已提交
239
### Intent
C
CyC2018 已提交
240

C
CyC2018 已提交
241
在创建一个对象时不向客户暴露内部细节并提供一个创建对象的通用接口
C
CyC2018 已提交
242

C
CyC2018 已提交
243
### Class Diagram
C
CyC2018 已提交
244

C
CyC2018 已提交
245
简单工厂不是设计模式更像是一种编程习惯它把实例化的操作单独放到一个类中这个类就成为简单工厂类让简单工厂类来决定应该用哪个具体子类来实例化
C
CyC2018 已提交
246

C
CyC2018 已提交
247
这样做能把客户类和具体子类的实现解耦客户类不再需要知道有哪些子类以及应当实例化哪个子类客户类往往有多个如果不使用简单工厂那么所有的客户类都要知道所有子类的细节而且一旦子类发生改变例如增加子类那么所有的客户类都要进行修改
C
CyC2018 已提交
248

C
CyC2018 已提交
249
<div align="center"> <img src="../pics//c79da808-0f28-4a36-bc04-33ccc5b83c13.png"/> </div><br>
C
CyC2018 已提交
250

C
CyC2018 已提交
251
### Implementation
C
CyC2018 已提交
252 253

```java
C
CyC2018 已提交
254
public interface Product {
C
CyC2018 已提交
255 256 257 258
}
```

```java
C
CyC2018 已提交
259
public class ConcreteProduct implements Product {
C
CyC2018 已提交
260 261 262 263
}
```

```java
C
CyC2018 已提交
264
public class ConcreteProduct1 implements Product {
C
CyC2018 已提交
265 266 267 268
}
```

```java
C
CyC2018 已提交
269
public class ConcreteProduct2 implements Product {
C
CyC2018 已提交
270 271 272
}
```

C
CyC2018 已提交
273
以下的 Client 类包含了实例化的代码,这是一种错误的实现。如果在客户类中存在这种实例化代码,就需要考虑将代码放到简单工厂中。
C
CyC2018 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293

```java
public class Client {
    public static void main(String[] args) {
        int type = 1;
        Product product;
        if (type == 1) {
            product = new ConcreteProduct1();
        } else if (type == 2) {
            product = new ConcreteProduct2();
        } else {
            product = new ConcreteProduct();
        }
        // do something with the product
    }
}
```

以下的 SimpleFactory 是简单工厂实现,它被所有需要进行实例化的客户类调用。

C
CyC2018 已提交
294
```java
C
CyC2018 已提交
295 296 297 298 299 300 301 302 303
public class SimpleFactory {
    public Product createProduct(int type) {
        if (type == 1) {
            return new ConcreteProduct1();
        } else if (type == 2) {
            return new ConcreteProduct2();
        }
        return new ConcreteProduct();
    }
C
CyC2018 已提交
304 305 306 307
}
```

```java
C
CyC2018 已提交
308 309 310 311
public class Client {
    public static void main(String[] args) {
        SimpleFactory simpleFactory = new SimpleFactory();
        Product product = simpleFactory.createProduct(1);
C
CyC2018 已提交
312
        // do something with the product
C
CyC2018 已提交
313
    }
C
CyC2018 已提交
314 315 316
}
```

C
CyC2018 已提交
317
## 3. 工厂方法(Factory Method)
C
CyC2018 已提交
318

C
CyC2018 已提交
319
### Intent
C
CyC2018 已提交
320

C
CyC2018 已提交
321
定义了一个创建对象的接口,但由子类决定要实例化哪个类。工厂方法把实例化操作推迟到子类。
C
CyC2018 已提交
322

C
CyC2018 已提交
323
### Class Diagram
C
CyC2018 已提交
324 325 326

在简单工厂中,创建对象的是另一个类,而在工厂方法中,是由子类来创建对象。

C
CyC2018 已提交
327
下图中,Factory 有一个 doSomething() 方法,这个方法需要用到一个产品对象,这个产品对象由 factoryMethod() 方法创建。该方法是抽象的,需要由子类去实现。
C
CyC2018 已提交
328

C
CyC2018 已提交
329
<div align="center"> <img src="../pics//1818e141-8700-4026-99f7-900a545875f5.png"/> </div><br>
C
CyC2018 已提交
330

C
CyC2018 已提交
331
### Implementation
C
CyC2018 已提交
332 333

```java
C
CyC2018 已提交
334 335 336 337 338 339
public abstract class Factory {
    abstract public Product factoryMethod();
    public void doSomething() {
        Product product = factoryMethod();
        // do something with the product
    }
C
CyC2018 已提交
340 341 342 343
}
```

```java
C
CyC2018 已提交
344 345 346 347
public class ConcreteFactory extends Factory {
    public Product factoryMethod() {
        return new ConcreteProduct();
    }
C
CyC2018 已提交
348 349 350 351
}
```

```java
C
CyC2018 已提交
352 353 354 355
public class ConcreteFactory1 extends Factory {
    public Product factoryMethod() {
        return new ConcreteProduct1();
    }
C
CyC2018 已提交
356 357 358 359
}
```

```java
C
CyC2018 已提交
360 361 362 363
public class ConcreteFactory2 extends Factory {
    public Product factoryMethod() {
        return new ConcreteProduct2();
    }
C
CyC2018 已提交
364 365 366
}
```

C
CyC2018 已提交
367
### JDK
C
CyC2018 已提交
368

C
CyC2018 已提交
369 370 371 372 373 374 375
- [java.util.Calendar](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--)
- [java.util.ResourceBundle](http://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-)
- [java.text.NumberFormat](http://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--)
- [java.nio.charset.Charset](http://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-)
- [java.net.URLStreamHandlerFactory](http://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html#createURLStreamHandler-java.lang.String-)
- [java.util.EnumSet](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of-E-)
- [javax.xml.bind.JAXBContext](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--)
C
CyC2018 已提交
376

C
CyC2018 已提交
377
## 4. 抽象工厂(Abstract Factory)
C
CyC2018 已提交
378

C
CyC2018 已提交
379
### Intent
C
CyC2018 已提交
380

C
CyC2018 已提交
381
提供一个接口,用于创建  **相关的对象家族** 。
C
CyC2018 已提交
382

C
CyC2018 已提交
383
### Class Diagram
C
CyC2018 已提交
384

C
CyC2018 已提交
385
抽象工厂模式创建的是对象家族,也就是很多对象而不是一个对象,并且这些对象是相关的,也就是说必须一起创建出来。而工厂方法模式只是用于创建一个对象,这和抽象工厂模式有很大不同。
C
CyC2018 已提交
386

C
CyC2018 已提交
387
抽象工厂模式用到了工厂方法模式来创建单一对象,AbstractFactory 中的 createProductA() 和 createProductB() 方法都是让子类来实现,这两个方法单独来看就是在创建一个对象,这符合工厂方法模式的定义。
C
CyC2018 已提交
388

C
CyC2018 已提交
389
至于创建对象的家族这一概念是在 Client 体现,Client 要通过 AbstractFactory 同时调用两个方法来创建出两个对象,在这里这两个对象就有很大的相关性,Client 需要同时创建出这两个对象。
C
CyC2018 已提交
390

C
CyC2018 已提交
391 392 393
从高层次来看,抽象工厂使用了组合,即 Cilent 组合了 AbstractFactory,而工厂方法模式使用了继承。

<div align="center"> <img src="../pics//8668a3e1-c9c7-4fcb-98b2-a96a5d841579.png"/> </div><br>
C
CyC2018 已提交
394

C
CyC2018 已提交
395
### Implementation
C
CyC2018 已提交
396 397

```java
C
CyC2018 已提交
398
public class AbstractProductA {
C
CyC2018 已提交
399 400 401 402
}
```

```java
C
CyC2018 已提交
403
public class AbstractProductB {
C
CyC2018 已提交
404 405 406 407
}
```

```java
C
CyC2018 已提交
408
public class ProductA1 extends AbstractProductA {
C
CyC2018 已提交
409 410 411 412
}
```

```java
C
CyC2018 已提交
413
public class ProductA2 extends AbstractProductA {
C
CyC2018 已提交
414 415 416 417
}
```

```java
C
CyC2018 已提交
418
public class ProductB1 extends AbstractProductB {
C
CyC2018 已提交
419 420 421 422
}
```

```java
C
CyC2018 已提交
423
public class ProductB2 extends AbstractProductB {
C
CyC2018 已提交
424 425 426 427
}
```

```java
C
CyC2018 已提交
428 429 430
public abstract class AbstractFactory {
    abstract AbstractProductA createProductA();
    abstract AbstractProductB createProductB();
C
CyC2018 已提交
431 432 433 434
}
```

```java
C
CyC2018 已提交
435 436 437 438
public class ConcreteFactory1 extends AbstractFactory {
    AbstractProductA createProductA() {
        return new ProductA1();
    }
C
CyC2018 已提交
439

C
CyC2018 已提交
440 441 442
    AbstractProductB createProductB() {
        return new ProductB1();
    }
C
CyC2018 已提交
443 444 445 446
}
```

```java
C
CyC2018 已提交
447 448 449 450
public class ConcreteFactory2 extends AbstractFactory {
    AbstractProductA createProductA() {
        return new ProductA2();
    }
C
CyC2018 已提交
451

C
CyC2018 已提交
452 453 454
    AbstractProductB createProductB() {
        return new ProductB2();
    }
C
CyC2018 已提交
455 456 457 458
}
```

```java
C
CyC2018 已提交
459 460 461 462 463 464 465
public class Client {
    public static void main(String[] args) {
        AbstractFactory abstractFactory = new ConcreteFactory1();
        AbstractProductA productA = abstractFactory.createProductA();
        AbstractProductB productB = abstractFactory.createProductB();
        // do something with productA and productB
    }
C
CyC2018 已提交
466 467 468
}
```

C
CyC2018 已提交
469
### JDK
C
CyC2018 已提交
470

C
CyC2018 已提交
471 472 473
- [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html)
- [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--)
- [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--)
C
CyC2018 已提交
474

C
CyC2018 已提交
475
## 5. 生成器(Builder)
C
CyC2018 已提交
476

C
CyC2018 已提交
477
### Intent
C
CyC2018 已提交
478

C
CyC2018 已提交
479
封装一个对象的构造过程,并允许按步骤构造。
C
CyC2018 已提交
480

C
CyC2018 已提交
481
### Class Diagram
C
CyC2018 已提交
482 483 484

<div align="center"> <img src="../pics//13b0940e-d1d7-4b17-af4f-b70cb0a75e08.png"/> </div><br>

C
CyC2018 已提交
485
### Implementation
C
CyC2018 已提交
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555

以下是一个简易的 StringBuilder 实现,参考了 JDK 1.8 源码。

```java
public class AbstractStringBuilder {
    protected char[] value;

    protected int count;

    public AbstractStringBuilder(int capacity) {
        count = 0;
        value = new char[capacity];
    }

    public AbstractStringBuilder append(char c) {
        ensureCapacityInternal(count + 1);
        value[count++] = c;
        return this;
    }

    private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code
        if (minimumCapacity - value.length > 0)
            expandCapacity(minimumCapacity);
    }

    void expandCapacity(int minimumCapacity) {
        int newCapacity = value.length * 2 + 2;
        if (newCapacity - minimumCapacity < 0)
            newCapacity = minimumCapacity;
        if (newCapacity < 0) {
            if (minimumCapacity < 0) // overflow
                throw new OutOfMemoryError();
            newCapacity = Integer.MAX_VALUE;
        }
        value = Arrays.copyOf(value, newCapacity);
    }
}
```

```java
public class StringBuilder extends AbstractStringBuilder {
    public StringBuilder() {
        super(16);
    }

    @Override
    public String toString() {
        // Create a copy, don't share the array
        return new String(value, 0, count);
    }
}
```

```java
public class Client {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        final int count = 26;
        for (int i = 0; i < count; i++) {
            sb.append((char) ('a' + i));
        }
        System.out.println(sb.toString());
    }
}
```

```html
abcdefghijklmnopqrstuvwxyz
```
C
CyC2018 已提交
556

C
CyC2018 已提交
557
### JDK
C
CyC2018 已提交
558

C
CyC2018 已提交
559 560 561 562 563
- [java.lang.StringBuilder](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html)
- [java.nio.ByteBuffer](http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#put-byte-)
- [java.lang.StringBuffer](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#append-boolean-)
- [java.lang.Appendable](http://docs.oracle.com/javase/8/docs/api/java/lang/Appendable.html)
- [Apache Camel builders](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder)
C
CyC2018 已提交
564

C
CyC2018 已提交
565
## 6. 原型模式(Prototype)
C
CyC2018 已提交
566

C
CyC2018 已提交
567
### Intent
C
CyC2018 已提交
568

C
CyC2018 已提交
569 570
使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象。

C
CyC2018 已提交
571
### Class Diagram
C
CyC2018 已提交
572 573 574

<div align="center"> <img src="../pics//a40661e4-1a71-46d2-a158-ff36f7fc3331.png"/> </div><br>

C
CyC2018 已提交
575
### Implementation
C
CyC2018 已提交
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616

```java
public abstract class Prototype {
    abstract Prototype myClone();
}
```

```java
public class ConcretePrototype extends Prototype {

    private String filed;

    public ConcretePrototype(String filed) {
        this.filed = filed;
    }

    @Override
    Prototype myClone() {
        return new ConcretePrototype(filed);
    }

    @Override
    public String toString() {
        return filed;
    }
}
```

```java
public class Client {
    public static void main(String[] args) {
        Prototype prototype = new ConcretePrototype("abc");
        Prototype clone = prototype.myClone();
        System.out.println(clone.toString());
    }
}
```

```html
abc
```
C
CyC2018 已提交
617

C
CyC2018 已提交
618
### JDK
C
CyC2018 已提交
619

C
CyC2018 已提交
620
- [java.lang.Object#clone()](http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#clone%28%29)
C
CyC2018 已提交
621

C
CyC2018 已提交
622
# 三、行为型
C
CyC2018 已提交
623

C
CyC2018 已提交
624
## 1. 责任链(Chain Of Responsibility)
C
CyC2018 已提交
625

C
CyC2018 已提交
626
### Intent
C
CyC2018 已提交
627

C
CyC2018 已提交
628
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链发送该请求,直到有一个对象处理它为止。
C
CyC2018 已提交
629

C
CyC2018 已提交
630
### Class Diagram
C
CyC2018 已提交
631 632 633 634 635

- Handler:定义处理请求的接口,并且实现后继链(successor)

<div align="center"> <img src="../pics//691f11eb-31a7-46be-9de1-61f433c4b3c7.png"/> </div><br>

C
CyC2018 已提交
636
### Implementation
C
CyC2018 已提交
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730

```java
public abstract class Handler {
    protected Handler successor;

    public Handler(Handler successor) {
        this.successor = successor;
    }

    protected abstract void handleRequest(Request request);
}
```

```java
public class ConcreteHandler1 extends Handler {
    public ConcreteHandler1(Handler successor) {
        super(successor);
    }

    @Override
    protected void handleRequest(Request request) {
        if (request.getType() == RequestType.type1) {
            System.out.println(request.getName() + " is handle by ConcreteHandler1");
            return;
        }
        if (successor != null) {
            successor.handleRequest(request);
        }
    }
}
```

```java
public class ConcreteHandler2 extends Handler{
    public ConcreteHandler2(Handler successor) {
        super(successor);
    }

    @Override
    protected void handleRequest(Request request) {
        if (request.getType() == RequestType.type2) {
            System.out.println(request.getName() + " is handle by ConcreteHandler2");
            return;
        }
        if (successor != null) {
            successor.handleRequest(request);
        }
    }
}
```

```java
public class Request {
    private RequestType type;
    private String name;

    public Request(RequestType type, String name) {
        this.type = type;
        this.name = name;
    }

    public RequestType getType() {
        return type;
    }

    public String getName() {
        return name;
    }
}
```

```java
public enum RequestType {
    type1, type2
}
```

```java
public class Client {
    public static void main(String[] args) {
        Handler handler1 = new ConcreteHandler1(null);
        Handler handler2 = new ConcreteHandler2(handler1);
        Request request1 = new Request(RequestType.type1, "request1");
        handler2.handleRequest(request1);
        Request request2 = new Request(RequestType.type2, "request2");
        handler2.handleRequest(request2);
    }
}
```

```html
request1 is handle by ConcreteHandler1
request2 is handle by ConcreteHandler2
```
C
CyC2018 已提交
731

C
CyC2018 已提交
732
### JDK
C
CyC2018 已提交
733

C
CyC2018 已提交
734 735 736
- [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29)
- [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html)
- [javax.servlet.Filter#doFilter()](http://docs.oracle.com/javaee/7/api/javax/servlet/Filter.html#doFilter-javax.servlet.ServletRequest-javax.servlet.ServletResponse-javax.servlet.FilterChain-)
C
CyC2018 已提交
737

C
CyC2018 已提交
738
## 2. 命令(Command)
C
CyC2018 已提交
739

C
CyC2018 已提交
740 741 742
### Intent

将命令封装成对象中,具有以下作用:
C
CyC2018 已提交
743

C
CyC2018 已提交
744 745 746 747
- 使用命令来参数化其它对象
- 将命令放入队列中进行排队
- 将命令的操作记录到日志中
- 支持可撤销的操作
C
CyC2018 已提交
748

C
CyC2018 已提交
749
### Class Diagram
C
CyC2018 已提交
750 751 752 753 754 755 756 757

- Command:命令
- Receiver:命令接收者,也就是命令真正的执行者
- Invoker:通过它来调用命令
- Client:可以设置命令与命令的接收者

<div align="center"> <img src="../pics//ae1b27b8-bc13-42e7-ac12-a2242e125499.png"/> </div><br>

C
CyC2018 已提交
758
### Implementation
C
CyC2018 已提交
759

C
CyC2018 已提交
760
设计一个遥控器,可以控制电灯开关。
C
CyC2018 已提交
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858

<div align="center"> <img src="../pics//e6bded8e-41a0-489a-88a6-638e88ab7666.jpg"/> </div><br>

```java
public interface Command {
    void execute();
}
```

```java
public class LightOnCommand implements Command {
    Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.on();
    }
}
```

```java
public class LightOffCommand implements Command {
    Light light;

    public LightOffCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.off();
    }
}
```

```java
public class Light {

    public void on() {
        System.out.println("Light is on!");
    }

    public void off() {
        System.out.println("Light is off!");
    }
}
```

```java
/**
 * 遥控器
 */
public class Invoker {
    private Command[] onCommands;
    private Command[] offCommands;
    private final int slotNum = 7;

    public Invoker() {
        this.onCommands = new Command[slotNum];
        this.offCommands = new Command[slotNum];
    }

    public void setOnCommand(Command command, int slot) {
        onCommands[slot] = command;
    }

    public void setOffCommand(Command command, int slot) {
        offCommands[slot] = command;
    }

    public void onButtonWasPushed(int slot) {
        onCommands[slot].execute();
    }

    public void offButtonWasPushed(int slot) {
        offCommands[slot].execute();
    }
}
```

```java
public class Client {
    public static void main(String[] args) {
        Invoker invoker = new Invoker();
        Light light = new Light();
        Command lightOnCommand = new LightOnCommand(light);
        Command lightOffCommand = new LightOffCommand(light);
        invoker.setOnCommand(lightOnCommand, 0);
        invoker.setOffCommand(lightOffCommand, 0);
        invoker.onButtonWasPushed(0);
        invoker.offButtonWasPushed(0);
    }
}
```
C
CyC2018 已提交
859

C
CyC2018 已提交
860
### JDK
C
CyC2018 已提交
861

C
CyC2018 已提交
862 863 864
- [java.lang.Runnable](http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html)
- [Netflix Hystrix](https://github.com/Netflix/Hystrix/wiki)
- [javax.swing.Action](http://docs.oracle.com/javase/8/docs/api/javax/swing/Action.html)
C
CyC2018 已提交
865

C
CyC2018 已提交
866
## 3. 解释器(Interpreter)
C
CyC2018 已提交
867

C
CyC2018 已提交
868
### Intent
C
CyC2018 已提交
869 870 871

为语言创建解释器,通常由语言的语法和语法分析来定义。

C
CyC2018 已提交
872
### Class Diagram
C
CyC2018 已提交
873

C
CyC2018 已提交
874 875
- TerminalExpression:终结符表达式,每个终结符都需要一个 TerminalExpression。
- Context:上下文,包含解释器之外的一些全局信息。
C
CyC2018 已提交
876 877 878

<div align="center"> <img src="../pics//794239e3-4baf-4aad-92df-f02f59b2a6fe.png"/> </div><br>

C
CyC2018 已提交
879
### Implementation
C
CyC2018 已提交
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982

以下是一个规则检验器实现,具有 and 和 or 规则,通过规则可以构建一颗解析树,用来检验一个文本是否满足解析树定义的规则。

例如一颗解析树为 D And (A Or (B C)),文本 "D A" 满足该解析树定义的规则。

这里的 Context 指的是 String。

```java
public abstract class Expression {
    public abstract boolean interpret(String str);
}
```

```java
public class TerminalExpression extends Expression {

    private String literal = null;

    public TerminalExpression(String str) {
        literal = str;
    }

    public boolean interpret(String str) {
        StringTokenizer st = new StringTokenizer(str);
        while (st.hasMoreTokens()) {
            String test = st.nextToken();
            if (test.equals(literal)) {
                return true;
            }
        }
        return false;
    }
}
```

```java
public class AndExpression extends Expression {

    private Expression expression1 = null;
    private Expression expression2 = null;

    public AndExpression(Expression expression1, Expression expression2) {
        this.expression1 = expression1;
        this.expression2 = expression2;
    }

    public boolean interpret(String str) {
        return expression1.interpret(str) && expression2.interpret(str);
    }
}
```

```java
public class OrExpression extends Expression {
    private Expression expression1 = null;
    private Expression expression2 = null;

    public OrExpression(Expression expression1, Expression expression2) {
        this.expression1 = expression1;
        this.expression2 = expression2;
    }

    public boolean interpret(String str) {
        return expression1.interpret(str) || expression2.interpret(str);
    }
}
```

```java
public class Client {

    /**
     * 构建解析树
     */
    public static Expression buildInterpreterTree() {
        // Literal
        Expression terminal1 = new TerminalExpression("A");
        Expression terminal2 = new TerminalExpression("B");
        Expression terminal3 = new TerminalExpression("C");
        Expression terminal4 = new TerminalExpression("D");
        // B C
        Expression alternation1 = new OrExpression(terminal2, terminal3);
        // A Or (B C)
        Expression alternation2 = new OrExpression(terminal1, alternation1);
        // D And (A Or (B C))
        return new AndExpression(terminal4, alternation2);
    }

    public static void main(String[] args) {
        Expression define = buildInterpreterTree();
        String context1 = "D A";
        String context2 = "A B";
        System.out.println(define.interpret(context1));
        System.out.println(define.interpret(context2));
    }
}
```

```html
true
false
```

C
CyC2018 已提交
983
### JDK
C
CyC2018 已提交
984

C
CyC2018 已提交
985 986 987 988
- [java.util.Pattern](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)
- [java.text.Normalizer](http://docs.oracle.com/javase/8/docs/api/java/text/Normalizer.html)
- All subclasses of [java.text.Format](http://docs.oracle.com/javase/8/docs/api/java/text/Format.html)
- [javax.el.ELResolver](http://docs.oracle.com/javaee/7/api/javax/el/ELResolver.html)
C
CyC2018 已提交
989

C
CyC2018 已提交
990
## 4. 迭代器(Iterator)
C
CyC2018 已提交
991

C
CyC2018 已提交
992
### Intent
C
CyC2018 已提交
993

C
CyC2018 已提交
994 995
提供一种顺序访问聚合对象元素的方法,并且不暴露聚合对象的内部表示。

C
CyC2018 已提交
996
### Class Diagram
C
CyC2018 已提交
997

C
CyC2018 已提交
998 999 1000 1001
- Aggregate 是聚合类,其中 createIterator() 方法可以产生一个 Iterator;
- Iterator 主要定义了 hasNext() 和 next() 方法。
- Client 组合了 Aggregate,为了迭代遍历 Aggregate,也需要组合 Iterator。

C
CyC2018 已提交
1002 1003
<div align="center"> <img src="../pics//b0f61ac2-a4b6-4042-9cf0-ccf4238c1ff7.png"/> </div><br>

C
CyC2018 已提交
1004
### Implementation
C
CyC2018 已提交
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032

```java
public interface Aggregate {
    Iterator createIterator();
}
```

```java
public class ConcreteAggregate implements Aggregate {

    private Integer[] items;

    public ConcreteAggregate() {
        items = new Integer[10];
        for (int i = 0; i < items.length; i++) {
            items[i] = i;
        }
    }

    @Override
    public Iterator createIterator() {
        return new ConcreteIterator<Integer>(items);
    }
}
```

```java
public interface Iterator<Item> {
C
CyC2018 已提交
1033

C
CyC2018 已提交
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
    Item next();

    boolean hasNext();
}
```

```java
public class ConcreteIterator<Item> implements Iterator {

    private Item[] items;
    private int position = 0;

    public ConcreteIterator(Item[] items) {
        this.items = items;
    }

    @Override
    public Object next() {
        return items[position++];
    }

    @Override
    public boolean hasNext() {
        return position < items.length;
    }
}
```

```java
public class Client {
C
CyC2018 已提交
1064

C
CyC2018 已提交
1065 1066 1067 1068 1069 1070 1071 1072 1073
    public static void main(String[] args) {
        Aggregate aggregate = new ConcreteAggregate();
        Iterator<Integer> iterator = aggregate.createIterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
```
C
CyC2018 已提交
1074

C
CyC2018 已提交
1075
### JDK
C
CyC2018 已提交
1076

C
CyC2018 已提交
1077 1078
- [java.util.Iterator](http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html)
- [java.util.Enumeration](http://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html)
C
CyC2018 已提交
1079

C
CyC2018 已提交
1080
## 5. 中介者(Mediator)
C
CyC2018 已提交
1081

C
CyC2018 已提交
1082
### Intent
C
CyC2018 已提交
1083

C
CyC2018 已提交
1084 1085
集中相关对象之间复杂的沟通和控制方式。

C
CyC2018 已提交
1086
### Class Diagram
C
CyC2018 已提交
1087 1088 1089 1090 1091 1092

- Mediator:中介者,定义一个接口用于与各同事(Colleague)对象通信。
- Colleague:同事,相关对象

<div align="center"> <img src="../pics//d0afdd23-c9a5-4d1c-9b3d-404bff3bd0d1.png"/> </div><br>

C
CyC2018 已提交
1093
### Implementation
C
CyC2018 已提交
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239

Alarm(闹钟)、CoffeePot(咖啡壶)、Calendar(日历)、Sprinkler(喷头)是一组相关的对象,在某个对象的事件产生时需要去操作其它对象,形成了下面这种依赖结构:

<div align="center"> <img src="../pics//82cfda3b-b53b-4c89-9fdb-26dd2db0cd02.jpg"/> </div><br>

使用中介者模式可以将复杂的依赖结构变成星形结构:

<div align="center"> <img src="../pics//5359cbf5-5a79-4874-9b17-f23c53c2cb80.jpg"/> </div><br>

```java
public abstract class Colleague {
    public abstract void onEvent(Mediator mediator);
}
```

```java
public class Alarm extends Colleague {

    @Override
    public void onEvent(Mediator mediator) {
        mediator.doEvent("alarm");
    }

    public void doAlarm() {
        System.out.println("doAlarm()");
    }
}
```

```java
public class CoffeePot extends Colleague {
    @Override
    public void onEvent(Mediator mediator) {
        mediator.doEvent("coffeePot");
    }

    public void doCoffeePot() {
        System.out.println("doCoffeePot()");
    }
}
```

```java
public class Calender extends Colleague {
    @Override
    public void onEvent(Mediator mediator) {
        mediator.doEvent("calender");
    }

    public void doCalender() {
        System.out.println("doCalender()");
    }
}
```

```java
public class Sprinkler extends Colleague {
    @Override
    public void onEvent(Mediator mediator) {
        mediator.doEvent("sprinkler");
    }

    public void doSprinkler() {
        System.out.println("doSprinkler()");
    }
}
```

```java
public abstract class Mediator {
    public abstract void doEvent(String eventType);
}
```

```java
public class ConcreteMediator extends Mediator {
    private Alarm alarm;
    private CoffeePot coffeePot;
    private Calender calender;
    private Sprinkler sprinkler;

    public ConcreteMediator(Alarm alarm, CoffeePot coffeePot, Calender calender, Sprinkler sprinkler) {
        this.alarm = alarm;
        this.coffeePot = coffeePot;
        this.calender = calender;
        this.sprinkler = sprinkler;
    }

    @Override
    public void doEvent(String eventType) {
        switch (eventType) {
            case "alarm":
                doAlarmEvent();
                break;
            case "coffeePot":
                doCoffeePotEvent();
                break;
            case "calender":
                doCalenderEvent();
                break;
            default:
                doSprinklerEvent();
        }
    }

    public void doAlarmEvent() {
        alarm.doAlarm();
        coffeePot.doCoffeePot();
        calender.doCalender();
        sprinkler.doSprinkler();
    }

    public void doCoffeePotEvent() {
        // ...
    }

    public void doCalenderEvent() {
        // ...
    }

    public void doSprinklerEvent() {
        // ...
    }
}
```

```java
public class Client {
    public static void main(String[] args) {
        Alarm alarm = new Alarm();
        CoffeePot coffeePot = new CoffeePot();
        Calender calender = new Calender();
        Sprinkler sprinkler = new Sprinkler();
        Mediator mediator = new ConcreteMediator(alarm, coffeePot, calender, sprinkler);
        // 闹钟事件到达,调用中介者就可以操作相关对象
        alarm.onEvent(mediator);
    }
}
```

```java
doAlarm()
doCoffeePot()
doCalender()
doSprinkler()
```
C
CyC2018 已提交
1240

C
CyC2018 已提交
1241
### JDK
C
CyC2018 已提交
1242

C
CyC2018 已提交
1243 1244 1245 1246 1247
- All scheduleXXX() methods of [java.util.Timer](http://docs.oracle.com/javase/8/docs/api/java/util/Timer.html)
- [java.util.concurrent.Executor#execute()](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-)
- submit() and invokeXXX() methods of [java.util.concurrent.ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html)
- scheduleXXX() methods of [java.util.concurrent.ScheduledExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html)
- [java.lang.reflect.Method#invoke()](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#invoke-java.lang.Object-java.lang.Object...-)
C
CyC2018 已提交
1248

C
CyC2018 已提交
1249
## 6. 备忘录(Memento)
C
CyC2018 已提交
1250

C
CyC2018 已提交
1251
### Intent
C
CyC2018 已提交
1252 1253 1254

在不违反封装的情况下获得对象的内部状态,从而在需要时可以将对象恢复到最初状态。

C
CyC2018 已提交
1255
### Class Diagram
C
CyC2018 已提交
1256 1257 1258 1259 1260 1261 1262

- Originator:原始对象
- Caretaker:负责保存好备忘录
- Menento:备忘录,存储原始对象的的状态。备忘录实际上有两个接口,一个是提供给 Caretaker 的窄接口:它只能将备忘录传递给其它对象;一个是提供给 Originator 的宽接口,允许它访问到先前状态所需的所有数据。理想情况是只允许 Originator 访问本备忘录的内部状态。

<div align="center"> <img src="../pics//867e93eb-3161-4f39-b2d2-c0cd3788e194.png"/> </div><br>

C
CyC2018 已提交
1263
### Implementation
C
CyC2018 已提交
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330

以下实现了一个简单计算器程序,可以输入两个值,然后计算这两个值的和。备忘录模式允许将这两个值存储起来,然后在某个时刻用存储的状态进行恢复。

实现参考:[Memento Pattern - Calculator Example - Java Sourcecode](https://www.oodesign.com/memento-pattern-calculator-example-java-sourcecode.html)

```java
/**
 * Originator Interface
 */
public interface Calculator {

    // Create Memento
    PreviousCalculationToCareTaker backupLastCalculation();

    // setMemento
    void restorePreviousCalculation(PreviousCalculationToCareTaker memento);

    int getCalculationResult();

    void setFirstNumber(int firstNumber);

    void setSecondNumber(int secondNumber);
}
```

```java
/**
 * Originator Implementation
 */
public class CalculatorImp implements Calculator {

    private int firstNumber;
    private int secondNumber;

    @Override
    public PreviousCalculationToCareTaker backupLastCalculation() {
        // create a memento object used for restoring two numbers
        return new PreviousCalculationImp(firstNumber, secondNumber);
    }

    @Override
    public void restorePreviousCalculation(PreviousCalculationToCareTaker memento) {
        this.firstNumber = ((PreviousCalculationToOriginator) memento).getFirstNumber();
        this.secondNumber = ((PreviousCalculationToOriginator) memento).getSecondNumber();
    }

    @Override
    public int getCalculationResult() {
        // result is adding two numbers
        return firstNumber + secondNumber;
    }

    @Override
    public void setFirstNumber(int firstNumber) {
        this.firstNumber = firstNumber;
    }

    @Override
    public void setSecondNumber(int secondNumber) {
        this.secondNumber = secondNumber;
    }
}
```

```java
/**
 * Memento Interface to Originator
C
CyC2018 已提交
1331
 *
C
CyC2018 已提交
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
 * This interface allows the originator to restore its state
 */
public interface PreviousCalculationToOriginator {
    int getFirstNumber();
    int getSecondNumber();
}
```

```java
/**
 *  Memento interface to CalculatorOperator (Caretaker)
 */
public interface PreviousCalculationToCareTaker {
    // no operations permitted for the caretaker
}
```

```java
/**
 * Memento Object Implementation
 * <p>
 * Note that this object implements both interfaces to Originator and CareTaker
 */
public class PreviousCalculationImp implements PreviousCalculationToCareTaker,
        PreviousCalculationToOriginator {

    private int firstNumber;
    private int secondNumber;

    public PreviousCalculationImp(int firstNumber, int secondNumber) {
        this.firstNumber = firstNumber;
        this.secondNumber = secondNumber;
    }

    @Override
    public int getFirstNumber() {
        return firstNumber;
    }

    @Override
    public int getSecondNumber() {
        return secondNumber;
    }
}
```

```java
/**
 * CareTaker object
 */
public class Client {

    public static void main(String[] args) {
        // program starts
        Calculator calculator = new CalculatorImp();

        // assume user enters two numbers
        calculator.setFirstNumber(10);
        calculator.setSecondNumber(100);

        // find result
        System.out.println(calculator.getCalculationResult());

        // Store result of this calculation in case of error
        PreviousCalculationToCareTaker memento = calculator.backupLastCalculation();

        // user enters a number
        calculator.setFirstNumber(17);

        // user enters a wrong second number and calculates result
        calculator.setSecondNumber(-290);

        // calculate result
        System.out.println(calculator.getCalculationResult());

        // user hits CTRL + Z to undo last operation and see last result
        calculator.restorePreviousCalculation(memento);

C
CyC2018 已提交
1410
        // result restored
C
CyC2018 已提交
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
        System.out.println(calculator.getCalculationResult());
    }
}
```

```html
110
-273
110
```

C
CyC2018 已提交
1422
### JDK
C
CyC2018 已提交
1423

C
CyC2018 已提交
1424
- java.io.Serializable
C
CyC2018 已提交
1425

C
CyC2018 已提交
1426
## 7. 观察者(Observer)
C
CyC2018 已提交
1427

C
CyC2018 已提交
1428
### Intent
C
CyC2018 已提交
1429 1430 1431

定义对象之间的一对多依赖,当一个对象状态改变时,它的所有依赖都会收到通知并且自动更新状态。

C
CyC2018 已提交
1432 1433 1434 1435
主题(Subject)是被观察的对象,而其所有依赖者(Observer)称为观察者。

<div align="center"> <img src="../pics//7a3c6a30-c735-4edb-8115-337288a4f0f2.jpg" width="600"/> </div><br>

C
CyC2018 已提交
1436
### Class Diagram
C
CyC2018 已提交
1437

C
CyC2018 已提交
1438
主题(Subject)具有注册和移除观察者、并通知所有观察者的功能,主题是通过维护一张观察者列表来实现这些操作的。
C
CyC2018 已提交
1439 1440 1441

观察者(Observer)的注册功能需要调用主题的 registerObserver() 方法。

C
CyC2018 已提交
1442
<div align="center"> <img src="../pics//0df5d84c-e7ca-4e3a-a688-bb8e68894467.png"/> </div><br>
C
CyC2018 已提交
1443

C
CyC2018 已提交
1444
### Implementation
C
CyC2018 已提交
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553

天气数据布告板会在天气信息发生改变时更新其内容,布告板有多个,并且在将来会继续增加。

<div align="center"> <img src="../pics//b1df9732-86ce-4d69-9f06-fba1db7b3b5a.jpg"/> </div><br>

```java
public interface Subject {
    void resisterObserver(Observer o);

    void removeObserver(Observer o);

    void notifyObserver();
}
```

```java
public class WeatherData implements Subject {
    private List<Observer> observers;
    private float temperature;
    private float humidity;
    private float pressure;

    public WeatherData() {
        observers = new ArrayList<>();
    }

    public void setMeasurements(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        notifyObserver();
    }

    @Override
    public void resisterObserver(Observer o) {
        observers.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        int i = observers.indexOf(o);
        if (i >= 0) {
            observers.remove(i);
        }
    }

    @Override
    public void notifyObserver() {
        for (Observer o : observers) {
            o.update(temperature, humidity, pressure);
        }
    }
}
```

```java
public interface Observer {
    void update(float temp, float humidity, float pressure);
}
```

```java
public class StatisticsDisplay implements Observer {

    public StatisticsDisplay(Subject weatherData) {
        weatherData.resisterObserver(this);
    }

    @Override
    public void update(float temp, float humidity, float pressure) {
        System.out.println("StatisticsDisplay.update: " + temp + " " + humidity + " " + pressure);
    }
}
```

```java
public class CurrentConditionsDisplay implements Observer {

    public CurrentConditionsDisplay(Subject weatherData) {
        weatherData.resisterObserver(this);
    }

    @Override
    public void update(float temp, float humidity, float pressure) {
        System.out.println("CurrentConditionsDisplay.update: " + temp + " " + humidity + " " + pressure);
    }
}
```

```java
public class WeatherStation {
    public static void main(String[] args) {
        WeatherData weatherData = new WeatherData();
        CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay(weatherData);
        StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData);

        weatherData.setMeasurements(0, 0, 0);
        weatherData.setMeasurements(1, 1, 1);
    }
}
```

```html
CurrentConditionsDisplay.update: 0.0 0.0 0.0
StatisticsDisplay.update: 0.0 0.0 0.0
CurrentConditionsDisplay.update: 1.0 1.0 1.0
StatisticsDisplay.update: 1.0 1.0 1.0
```

C
CyC2018 已提交
1554
### JDK
C
CyC2018 已提交
1555

C
CyC2018 已提交
1556 1557 1558 1559
- [java.util.Observer](http://docs.oracle.com/javase/8/docs/api/java/util/Observer.html)
- [java.util.EventListener](http://docs.oracle.com/javase/8/docs/api/java/util/EventListener.html)
- [javax.servlet.http.HttpSessionBindingListener](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSessionBindingListener.html)
- [RxJava](https://github.com/ReactiveX/RxJava)
C
CyC2018 已提交
1560

C
CyC2018 已提交
1561 1562
## 8. 状态(State)

C
CyC2018 已提交
1563
### Intent
C
CyC2018 已提交
1564 1565 1566

允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它所属的类。

C
CyC2018 已提交
1567
### Class Diagram
C
CyC2018 已提交
1568

C
CyC2018 已提交
1569
<div align="center"> <img src="../pics//c5085437-54df-4304-b62d-44b961711ba7.png"/> </div><br>
C
CyC2018 已提交
1570

C
CyC2018 已提交
1571
### Implementation
C
CyC2018 已提交
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862

糖果销售机有多种状态,每种状态下销售机有不同的行为,状态可以发生转移,使得销售机的行为也发生改变。

<div align="center"> <img src="../pics//396be981-3f2c-4fd9-8101-dbf9c841504b.jpg" width="600"/> </div><br>

```java
public interface State {
    /**
     * 投入 25 分钱
     */
    void insertQuarter();

    /**
     * 退回 25 分钱
     */
    void ejectQuarter();

    /**
     * 转动曲柄
     */
    void turnCrank();

    /**
     * 发放糖果
     */
    void dispense();
}
```

```java
public class HasQuarterState implements State {

    private GumballMachine gumballMachine;

    public HasQuarterState(GumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }

    @Override
    public void insertQuarter() {
        System.out.println("You can't insert another quarter");
    }

    @Override
    public void ejectQuarter() {
        System.out.println("Quarter returned");
        gumballMachine.setState(gumballMachine.getNoQuarterState());
    }

    @Override
    public void turnCrank() {
        System.out.println("You turned...");
        gumballMachine.setState(gumballMachine.getSoldState());
    }

    @Override
    public void dispense() {
        System.out.println("No gumball dispensed");
    }
}
```

```java
public class NoQuarterState implements State {

    GumballMachine gumballMachine;

    public NoQuarterState(GumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }

    @Override
    public void insertQuarter() {
        System.out.println("You insert a quarter");
        gumballMachine.setState(gumballMachine.getHasQuarterState());
    }

    @Override
    public void ejectQuarter() {
        System.out.println("You haven't insert a quarter");
    }

    @Override
    public void turnCrank() {
        System.out.println("You turned, but there's no quarter");
    }

    @Override
    public void dispense() {
        System.out.println("You need to pay first");
    }
}
```

```java
public class SoldOutState implements State {

    GumballMachine gumballMachine;

    public SoldOutState(GumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }

    @Override
    public void insertQuarter() {
        System.out.println("You can't insert a quarter, the machine is sold out");
    }

    @Override
    public void ejectQuarter() {
        System.out.println("You can't eject, you haven't inserted a quarter yet");
    }

    @Override
    public void turnCrank() {
        System.out.println("You turned, but there are no gumballs");
    }

    @Override
    public void dispense() {
        System.out.println("No gumball dispensed");
    }
}
```

```java
public class SoldState implements State {

    GumballMachine gumballMachine;

    public SoldState(GumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }

    @Override
    public void insertQuarter() {
        System.out.println("Please wait, we're already giving you a gumball");
    }

    @Override
    public void ejectQuarter() {
        System.out.println("Sorry, you already turned the crank");
    }

    @Override
    public void turnCrank() {
        System.out.println("Turning twice doesn't get you another gumball!");
    }

    @Override
    public void dispense() {
        gumballMachine.releaseBall();
        if (gumballMachine.getCount() > 0) {
            gumballMachine.setState(gumballMachine.getNoQuarterState());
        } else {
            System.out.println("Oops, out of gumballs");
            gumballMachine.setState(gumballMachine.getSoldOutState());
        }
    }
}
```

```java
public class GumballMachine {

    private State soldOutState;
    private State noQuarterState;
    private State hasQuarterState;
    private State soldState;

    private State state;
    private int count = 0;

    public GumballMachine(int numberGumballs) {
        count = numberGumballs;
        soldOutState = new SoldOutState(this);
        noQuarterState = new NoQuarterState(this);
        hasQuarterState = new HasQuarterState(this);
        soldState = new SoldState(this);

        if (numberGumballs > 0) {
            state = noQuarterState;
        } else {
            state = soldOutState;
        }
    }

    public void insertQuarter() {
        state.insertQuarter();
    }

    public void ejectQuarter() {
        state.ejectQuarter();
    }

    public void turnCrank() {
        state.turnCrank();
        state.dispense();
    }

    public void setState(State state) {
        this.state = state;
    }

    public void releaseBall() {
        System.out.println("A gumball comes rolling out the slot...");
        if (count != 0) {
            count -= 1;
        }
    }

    public State getSoldOutState() {
        return soldOutState;
    }

    public State getNoQuarterState() {
        return noQuarterState;
    }

    public State getHasQuarterState() {
        return hasQuarterState;
    }

    public State getSoldState() {
        return soldState;
    }

    public int getCount() {
        return count;
    }
}
```

```java
public class Client {

    public static void main(String[] args) {
        GumballMachine gumballMachine = new GumballMachine(5);

        gumballMachine.insertQuarter();
        gumballMachine.turnCrank();

        gumballMachine.insertQuarter();
        gumballMachine.ejectQuarter();
        gumballMachine.turnCrank();

        gumballMachine.insertQuarter();
        gumballMachine.turnCrank();
        gumballMachine.insertQuarter();
        gumballMachine.turnCrank();
        gumballMachine.ejectQuarter();

        gumballMachine.insertQuarter();
        gumballMachine.insertQuarter();
        gumballMachine.turnCrank();
        gumballMachine.insertQuarter();
        gumballMachine.turnCrank();
        gumballMachine.insertQuarter();
        gumballMachine.turnCrank();
    }
}
```

```html
You insert a quarter
You turned...
A gumball comes rolling out the slot...
You insert a quarter
Quarter returned
You turned, but there's no quarter
You need to pay first
You insert a quarter
You turned...
A gumball comes rolling out the slot...
You insert a quarter
You turned...
A gumball comes rolling out the slot...
You haven't insert a quarter
You insert a quarter
You can't insert another quarter
You turned...
A gumball comes rolling out the slot...
You insert a quarter
You turned...
A gumball comes rolling out the slot...
Oops, out of gumballs
You can't insert a quarter, the machine is sold out
You turned, but there are no gumballs
No gumball dispensed
```

C
CyC2018 已提交
1863
## 9. 策略(Strategy)
C
CyC2018 已提交
1864

C
CyC2018 已提交
1865
### Intent
C
CyC2018 已提交
1866

C
CyC2018 已提交
1867 1868 1869 1870
定义一系列算法,封装每个算法,并使它们可以互换。

策略模式可以让算法独立于使用它的客户端。

C
CyC2018 已提交
1871
### Class Diagram
C
CyC2018 已提交
1872

C
CyC2018 已提交
1873
- Strategy 接口定义了一个算法族,它们都实现了  behavior() 方法。
C
CyC2018 已提交
1874
- Context 是使用到该算法族的类,其中的 doSomething() 方法会调用 behavior(),setStrategy(Strategy) 方法可以动态地改变 strategy 对象,也就是说能动态地改变 Context 所使用的算法。
C
CyC2018 已提交
1875

C
CyC2018 已提交
1876
<div align="center"> <img src="../pics//1fc969e4-0e7c-441b-b53c-01950d2f2be5.png"/> </div><br>
C
CyC2018 已提交
1877 1878 1879

### 与状态模式的比较

C
CyC2018 已提交
1880
状态模式的类图和策略模式类似,并且都是能够动态改变对象的行为。但是状态模式是通过状态转移来改变 Context 所组合的 State 对象,而策略模式是通过 Context 本身的决策来改变组合的 Strategy 对象。所谓的状态转移,是指 Context 在运行过程中由于一些条件发生改变而使得 State 对象发生改变,注意必须要是在运行过程中。
C
CyC2018 已提交
1881 1882

状态模式主要是用来解决状态转移的问题,当状态发生转移了,那么 Context 对象就会改变它的行为;而策略模式主要是用来封装一组可以互相替代的算法族,并且可以根据需要动态地去替换 Context 使用的算法。
C
CyC2018 已提交
1883

C
CyC2018 已提交
1884
### Implementation
C
CyC2018 已提交
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913

设计一个鸭子,它可以动态地改变叫声。这里的算法族是鸭子的叫声行为。

```java
public interface QuackBehavior {
    void quack();
}
```

```java
public class Quack implements QuackBehavior {
    @Override
    public void quack() {
        System.out.println("quack!");
    }
}
```

```java
public class Squeak implements QuackBehavior{
    @Override
    public void quack() {
        System.out.println("squeak!");
    }
}
```

```java
public class Duck {
C
CyC2018 已提交
1914

C
CyC2018 已提交
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
    private QuackBehavior quackBehavior;

    public void performQuack() {
        if (quackBehavior != null) {
            quackBehavior.quack();
        }
    }

    public void setQuackBehavior(QuackBehavior quackBehavior) {
        this.quackBehavior = quackBehavior;
    }
}
```

```java
public class Client {
C
CyC2018 已提交
1931

C
CyC2018 已提交
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
    public static void main(String[] args) {
        Duck duck = new Duck();
        duck.setQuackBehavior(new Squeak());
        duck.performQuack();
        duck.setQuackBehavior(new Quack());
        duck.performQuack();
    }
}
```

```html
squeak!
quack!
```
C
CyC2018 已提交
1946

C
CyC2018 已提交
1947
### JDK
C
CyC2018 已提交
1948

C
CyC2018 已提交
1949 1950 1951
- java.util.Comparator#compare()
- javax.servlet.http.HttpServlet
- javax.servlet.Filter#doFilter()
C
CyC2018 已提交
1952

C
CyC2018 已提交
1953
## 10. 模板方法(Template Method)
C
CyC2018 已提交
1954

C
CyC2018 已提交
1955
### Intent
C
CyC2018 已提交
1956

C
CyC2018 已提交
1957 1958 1959 1960
定义算法框架,并将一些步骤的实现延迟到子类。

通过模板方法,子类可以重新定义算法的某些步骤,而不用改变算法的结构。

C
CyC2018 已提交
1961
### Class Diagram
C
CyC2018 已提交
1962 1963 1964

<div align="center"> <img src="../pics//c3c1c0e8-3a78-4426-961f-b46dd0879dd8.png"/> </div><br>

C
CyC2018 已提交
1965
### Implementation
C
CyC2018 已提交
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995

冲咖啡和冲茶都有类似的流程,但是某些步骤会有点不一样,要求复用那些相同步骤的代码。

<div align="center"> <img src="../pics//11236498-1417-46ce-a1b0-e10054256955.png"/> </div><br>

```java
public abstract class CaffeineBeverage {

    final void prepareRecipe() {
        boilWater();
        brew();
        pourInCup();
        addCondiments();
    }

    abstract void brew();

    abstract void addCondiments();

    void boilWater() {
        System.out.println("boilWater");
    }

    void pourInCup() {
        System.out.println("pourInCup");
    }
}
```

```java
C
CyC2018 已提交
1996
public class Coffee extends CaffeineBeverage {
C
CyC2018 已提交
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
    @Override
    void brew() {
        System.out.println("Coffee.brew");
    }

    @Override
    void addCondiments() {
        System.out.println("Coffee.addCondiments");
    }
}
```

```java
C
CyC2018 已提交
2010
public class Tea extends CaffeineBeverage {
C
CyC2018 已提交
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
    @Override
    void brew() {
        System.out.println("Tea.brew");
    }

    @Override
    void addCondiments() {
        System.out.println("Tea.addCondiments");
    }
}
```

```java
public class Client {
    public static void main(String[] args) {
        CaffeineBeverage caffeineBeverage = new Coffee();
        caffeineBeverage.prepareRecipe();
        System.out.println("-----------");
        caffeineBeverage = new Tea();
        caffeineBeverage.prepareRecipe();
    }
}
```

```html
boilWater
Coffee.brew
pourInCup
Coffee.addCondiments
-----------
boilWater
Tea.brew
pourInCup
Tea.addCondiments
```
C
CyC2018 已提交
2046

C
CyC2018 已提交
2047
### JDK
C
CyC2018 已提交
2048

C
CyC2018 已提交
2049 2050 2051 2052
- java.util.Collections#sort()
- java.io.InputStream#skip()
- java.io.InputStream#read()
- java.util.AbstractList#indexOf()
C
CyC2018 已提交
2053

C
CyC2018 已提交
2054
## 11. 访问者(Visitor)
C
CyC2018 已提交
2055

C
CyC2018 已提交
2056
### Intent
C
CyC2018 已提交
2057

C
CyC2018 已提交
2058
为一个对象结构(比如组合结构)增加新能力。
C
CyC2018 已提交
2059

C
CyC2018 已提交
2060
### Class Diagram
C
CyC2018 已提交
2061 2062 2063 2064 2065 2066 2067

- Visitor:访问者,为每一个 ConcreteElement 声明一个 visit 操作
- ConcreteVisitor:具体访问者,存储遍历过程中的累计结果
- ObjectStructure:对象结构,可以是组合结构,或者是一个集合。

<div align="center"> <img src="../pics//ec923dc7-864c-47b0-a411-1f2c48d084de.png"/> </div><br>

C
CyC2018 已提交
2068
### Implementation
C
CyC2018 已提交
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254

```java
public interface Element {
    void accept(Visitor visitor);
}
```

```java
class CustomerGroup {

    private List<Customer> customers = new ArrayList<>();

    void accept(Visitor visitor) {
        for (Customer customer : customers) {
            customer.accept(visitor);
        }
    }

    void addCustomer(Customer customer) {
        customers.add(customer);
    }
}
```

```java
public class Customer implements Element {

    private String name;
    private List<Order> orders = new ArrayList<>();

    Customer(String name) {
        this.name = name;
    }

    String getName() {
        return name;
    }

    void addOrder(Order order) {
        orders.add(order);
    }

    public void accept(Visitor visitor) {
        visitor.visit(this);
        for (Order order : orders) {
            order.accept(visitor);
        }
    }
}
```

```java
public class Order implements Element {

    private String name;
    private List<Item> items = new ArrayList();

    Order(String name) {
        this.name = name;
    }

    Order(String name, String itemName) {
        this.name = name;
        this.addItem(new Item(itemName));
    }

    String getName() {
        return name;
    }

    void addItem(Item item) {
        items.add(item);
    }

    public void accept(Visitor visitor) {
        visitor.visit(this);

        for (Item item : items) {
            item.accept(visitor);
        }
    }
}
```

```java
public class Item implements Element {

    private String name;

    Item(String name) {
        this.name = name;
    }

    String getName() {
        return name;
    }

    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}
```

```java
public interface Visitor {
    void visit(Customer customer);

    void visit(Order order);

    void visit(Item item);
}
```

```java
public class GeneralReport implements Visitor {

    private int customersNo;
    private int ordersNo;
    private int itemsNo;

    public void visit(Customer customer) {
        System.out.println(customer.getName());
        customersNo++;
    }

    public void visit(Order order) {
        System.out.println(order.getName());
        ordersNo++;
    }

    public void visit(Item item) {
        System.out.println(item.getName());
        itemsNo++;
    }

    public void displayResults() {
        System.out.println("Number of customers: " + customersNo);
        System.out.println("Number of orders:    " + ordersNo);
        System.out.println("Number of items:     " + itemsNo);
    }
}
```

```java
public class Client {
    public static void main(String[] args) {
        Customer customer1 = new Customer("customer1");
        customer1.addOrder(new Order("order1", "item1"));
        customer1.addOrder(new Order("order2", "item1"));
        customer1.addOrder(new Order("order3", "item1"));

        Order order = new Order("order_a");
        order.addItem(new Item("item_a1"));
        order.addItem(new Item("item_a2"));
        order.addItem(new Item("item_a3"));
        Customer customer2 = new Customer("customer2");
        customer2.addOrder(order);

        CustomerGroup customers = new CustomerGroup();
        customers.addCustomer(customer1);
        customers.addCustomer(customer2);

        GeneralReport visitor = new GeneralReport();
        customers.accept(visitor);
        visitor.displayResults();
    }
}
```

```html
customer1
order1
item1
order2
item1
order3
item1
customer2
order_a
item_a1
item_a2
item_a3
Number of customers: 2
Number of orders:    4
Number of items:     6
```
C
CyC2018 已提交
2255

C
CyC2018 已提交
2256
### JDK
C
CyC2018 已提交
2257

C
CyC2018 已提交
2258 2259
- javax.lang.model.element.Element and javax.lang.model.element.ElementVisitor
- javax.lang.model.type.TypeMirror and javax.lang.model.type.TypeVisitor
C
CyC2018 已提交
2260

C
CyC2018 已提交
2261
## 12. 空对象(Null)
C
CyC2018 已提交
2262

C
CyC2018 已提交
2263
### Intent
C
CyC2018 已提交
2264

C
CyC2018 已提交
2265
使用什么都不做的空对象来代替 NULL。
C
CyC2018 已提交
2266

C
CyC2018 已提交
2267
一个方法返回 NULL,意味着方法的调用端需要去检查返回值是否是 NULL,这么做会导致非常多的冗余的检查代码。并且如果某一个调用端忘记了做这个检查返回值,而直接使用返回的对象,那么就有可能抛出空指针异常。
C
CyC2018 已提交
2268

C
CyC2018 已提交
2269
### Class Diagram
C
CyC2018 已提交
2270

C
CyC2018 已提交
2271
<div align="center"> <img src="../pics//dd3b289c-d90e-44a6-a44c-4880517eb1de.png"/> </div><br>
C
CyC2018 已提交
2272

C
CyC2018 已提交
2273
### Implementation
C
CyC2018 已提交
2274 2275

```java
C
CyC2018 已提交
2276 2277
public abstract class AbstractOperation {
    abstract void request();
C
CyC2018 已提交
2278 2279 2280 2281
}
```

```java
C
CyC2018 已提交
2282 2283 2284 2285 2286
public class RealOperation extends AbstractOperation {
    @Override
    void request() {
        System.out.println("do something");
    }
C
CyC2018 已提交
2287 2288 2289 2290
}
```

```java
C
CyC2018 已提交
2291 2292 2293 2294 2295
public class NullOperation extends AbstractOperation{
    @Override
    void request() {
        // do nothing
    }
C
CyC2018 已提交
2296 2297 2298 2299
}
```

```java
C
CyC2018 已提交
2300 2301 2302 2303 2304
public class Client {
    public static void main(String[] args) {
        AbstractOperation abstractOperation = func(-1);
        abstractOperation.request();
    }
C
CyC2018 已提交
2305

C
CyC2018 已提交
2306 2307 2308 2309 2310 2311
    public static AbstractOperation func(int para) {
        if (para < 0) {
            return new NullOperation();
        }
        return new RealOperation();
    }
C
CyC2018 已提交
2312 2313 2314
}
```

C
CyC2018 已提交
2315
# 四、结构型
C
CyC2018 已提交
2316

C
CyC2018 已提交
2317
## 1. 适配器(Adapter)
C
CyC2018 已提交
2318

C
CyC2018 已提交
2319
### Intent
C
CyC2018 已提交
2320 2321 2322

把一个类接口转换成另一个用户需要的接口。

C
CyC2018 已提交
2323
<div align="center"> <img src="../pics//3d5b828e-5c4d-48d8-a440-281e4a8e1c92.png"/> </div><br>
C
CyC2018 已提交
2324

C
CyC2018 已提交
2325
### Class Diagram
C
CyC2018 已提交
2326

C
CyC2018 已提交
2327
<div align="center"> <img src="../pics//0f754c1d-b5cb-48cd-90e0-4a86034290a1.png"/> </div><br>
C
CyC2018 已提交
2328

C
CyC2018 已提交
2329
### Implementation
C
CyC2018 已提交
2330

C
CyC2018 已提交
2331
鸭子(Duck)和火鸡(Turkey)拥有不同的叫声,Duck 的叫声调用 quack() 方法,而 Turkey 调用 gobble() 方法。
C
CyC2018 已提交
2332

C
CyC2018 已提交
2333
要求将 Turkey 的 gobble() 方法适配成 Duck 的 quack() 方法,从而让火鸡冒充鸭子!
C
CyC2018 已提交
2334 2335

```java
C
CyC2018 已提交
2336 2337
public interface Duck {
    void quack();
C
CyC2018 已提交
2338 2339 2340 2341
}
```

```java
C
CyC2018 已提交
2342 2343
public interface Turkey {
    void gobble();
C
CyC2018 已提交
2344 2345 2346 2347
}
```

```java
C
CyC2018 已提交
2348 2349 2350 2351 2352
public class WildTurkey implements Turkey {
    @Override
    public void gobble() {
        System.out.println("gobble!");
    }
C
CyC2018 已提交
2353 2354 2355 2356
}
```

```java
C
CyC2018 已提交
2357 2358
public class TurkeyAdapter implements Duck {
    Turkey turkey;
C
CyC2018 已提交
2359

C
CyC2018 已提交
2360 2361 2362
    public TurkeyAdapter(Turkey turkey) {
        this.turkey = turkey;
    }
C
CyC2018 已提交
2363

C
CyC2018 已提交
2364 2365 2366 2367
    @Override
    public void quack() {
        turkey.gobble();
    }
C
CyC2018 已提交
2368 2369 2370 2371
}
```

```java
C
CyC2018 已提交
2372 2373 2374 2375 2376 2377
public class Client {
    public static void main(String[] args) {
        Turkey turkey = new WildTurkey();
        Duck duck = new TurkeyAdapter(turkey);
        duck.quack();
    }
C
CyC2018 已提交
2378 2379 2380
}
```

C
CyC2018 已提交
2381
### JDK
C
CyC2018 已提交
2382

C
CyC2018 已提交
2383 2384 2385 2386
- [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29)
- [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-)
- [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-)
- [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-)
C
CyC2018 已提交
2387

C
CyC2018 已提交
2388
## 2. 桥接(Bridge)
C
CyC2018 已提交
2389

C
CyC2018 已提交
2390
### Intent
C
CyC2018 已提交
2391 2392 2393

将抽象与实现分离开来,使它们可以独立变化。

C
CyC2018 已提交
2394
### Class Diagram
C
CyC2018 已提交
2395 2396 2397 2398 2399 2400

- Abstraction:定义抽象类的接口
- Implementor:定义实现类接口

<div align="center"> <img src="../pics//c2cbf5d2-82af-4c78-bd43-495da5adf55f.png"/> </div><br>

C
CyC2018 已提交
2401
### Implementation
C
CyC2018 已提交
2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419

RemoteControl 表示遥控器,指代 Abstraction。

TV 表示电视,指代 Implementor。

桥接模式将遥控器和电视分离开来,从而可以独立改变遥控器或者电视的实现。

```java
public abstract class TV {
    public abstract void on();

    public abstract void off();

    public abstract void tuneChannel();
}
```

```java
C
CyC2018 已提交
2420
public class Sony extends TV {
C
CyC2018 已提交
2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438
    @Override
    public void on() {
        System.out.println("Sony.on()");
    }

    @Override
    public void off() {
        System.out.println("Sony.off()");
    }

    @Override
    public void tuneChannel() {
        System.out.println("Sony.tuneChannel()");
    }
}
```

```java
C
CyC2018 已提交
2439
public class RCA extends TV {
C
CyC2018 已提交
2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535
    @Override
    public void on() {
        System.out.println("RCA.on()");
    }

    @Override
    public void off() {
        System.out.println("RCA.off()");
    }

    @Override
    public void tuneChannel() {
        System.out.println("RCA.tuneChannel()");
    }
}
```

```java
public abstract class RemoteControl {
    protected TV tv;

    public RemoteControl(TV tv) {
        this.tv = tv;
    }

    public abstract void on();

    public abstract void off();

    public abstract void tuneChannel();
}
```

```java
public class ConcreteRemoteControl1 extends RemoteControl {
    public ConcreteRemoteControl1(TV tv) {
        super(tv);
    }

    @Override
    public void on() {
        System.out.println("ConcreteRemoteControl1.on()");
        tv.on();
    }

    @Override
    public void off() {
        System.out.println("ConcreteRemoteControl1.off()");
        tv.off();
    }

    @Override
    public void tuneChannel() {
        System.out.println("ConcreteRemoteControl1.tuneChannel()");
        tv.tuneChannel();
    }
}
```

```java
public class ConcreteRemoteControl2 extends RemoteControl {
    public ConcreteRemoteControl2(TV tv) {
        super(tv);
    }

    @Override
    public void on() {
        System.out.println("ConcreteRemoteControl2.on()");
        tv.on();
    }

    @Override
    public void off() {
        System.out.println("ConcreteRemoteControl2.off()");
        tv.off();
    }

    @Override
    public void tuneChannel() {
        System.out.println("ConcreteRemoteControl2.tuneChannel()");
        tv.tuneChannel();
    }
}
```

```java
public class Client {
    public static void main(String[] args) {
        RemoteControl remoteControl1 = new ConcreteRemoteControl1(new RCA());
        remoteControl1.on();
        remoteControl1.off();
        remoteControl1.tuneChannel();
    }
}
```

C
CyC2018 已提交
2536
### JDK
C
CyC2018 已提交
2537

C
CyC2018 已提交
2538 2539
- AWT (It provides an abstraction layer which maps onto the native OS the windowing support.)
- JDBC
C
CyC2018 已提交
2540

C
CyC2018 已提交
2541
## 3. 组合(Composite)
C
CyC2018 已提交
2542

C
CyC2018 已提交
2543
### Intent
C
CyC2018 已提交
2544

C
CyC2018 已提交
2545 2546
将对象组合成树形结构来表示“整体/部分”层次关系,允许用户以相同的方式处理单独对象和组合对象。

C
CyC2018 已提交
2547
### Class Diagram
C
CyC2018 已提交
2548 2549 2550 2551 2552 2553 2554

组件(Component)类是组合类(Composite)和叶子类(Leaf)的父类,可以把组合类看成是树的中间节点。

组合对象拥有一个或者多个组件对象,因此组合对象的操作可以委托给组件对象去处理,而组件对象可以是另一个组合对象或者叶子对象。

<div align="center"> <img src="../pics//3fb5b255-b791-45b6-8754-325c8741855a.png"/> </div><br>

C
CyC2018 已提交
2555
### Implementation
C
CyC2018 已提交
2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665

```java
public abstract class Component {
    protected String name;

    public Component(String name) {
        this.name = name;
    }

    public void print() {
        print(0);
    }

    abstract void print(int level);

    abstract public void add(Component component);

    abstract public void remove(Component component);
}
```

```java
public class Composite extends Component {

    private List<Component> child;

    public Composite(String name) {
        super(name);
        child = new ArrayList<>();
    }

    @Override
    void print(int level) {
        for (int i = 0; i < level; i++) {
            System.out.print("--");
        }
        System.out.println("Composite:" + name);
        for (Component component : child) {
            component.print(level + 1);
        }
    }

    @Override
    public void add(Component component) {
        child.add(component);
    }

    @Override
    public void remove(Component component) {
        child.remove(component);
    }
}
```

```java
public class Leaf extends Component {
    public Leaf(String name) {
        super(name);
    }

    @Override
    void print(int level) {
        for (int i = 0; i < level; i++) {
            System.out.print("--");
        }
        System.out.println("left:" + name);
    }

    @Override
    public void add(Component component) {
        throw new UnsupportedOperationException(); // 牺牲透明性换取单一职责原则,这样就不用考虑是叶子节点还是组合节点
    }

    @Override
    public void remove(Component component) {
        throw new UnsupportedOperationException();
    }
}
```

```java
public class Client {
    public static void main(String[] args) {
        Composite root = new Composite("root");
        Component node1 = new Leaf("1");
        Component node2 = new Composite("2");
        Component node3 = new Leaf("3");
        root.add(node1);
        root.add(node2);
        root.add(node3);
        Component node21 = new Leaf("21");
        Component node22 = new Composite("22");
        node2.add(node21);
        node2.add(node22);
        Component node221 = new Leaf("221");
        node22.add(node221);
        root.print();
    }
}
```

```html
Composite:root
--left:1
--Composite:2
----left:21
----Composite:22
------left:221
--left:3
```
C
CyC2018 已提交
2666

C
CyC2018 已提交
2667
### JDK
C
CyC2018 已提交
2668

C
CyC2018 已提交
2669 2670 2671 2672 2673
- javax.swing.JComponent#add(Component)
- java.awt.Container#add(Component)
- java.util.Map#putAll(Map)
- java.util.List#addAll(Collection)
- java.util.Set#addAll(Collection)
C
CyC2018 已提交
2674

C
CyC2018 已提交
2675
## 4. 装饰(Decorator)
C
CyC2018 已提交
2676

C
CyC2018 已提交
2677
### Intent
C
CyC2018 已提交
2678 2679 2680

为对象动态添加功能。

C
CyC2018 已提交
2681
### Class Diagram
C
CyC2018 已提交
2682

C
CyC2018 已提交
2683
装饰者(Decorator)和具体组件(ConcreteComponent)都继承自组件(Component),具体组件的方法实现不需要依赖于其它对象,而装饰者组合了一个组件,这样它可以装饰其它装饰者或者具体组件。所谓装饰,就是把这个装饰者套在被装饰者之上,从而动态扩展被装饰者的功能。装饰者的方法有一部分是自己的,这属于它的功能,然后调用被装饰者的方法实现,从而也保留了被装饰者的功能。可以看到,具体组件应当是装饰层次的最低层,因为只有具体组件的方法实现不需要依赖于其它对象。
C
CyC2018 已提交
2684 2685 2686

<div align="center"> <img src="../pics//137c593d-0a9e-47b8-a9e6-b71f540b82dd.png"/> </div><br>

C
CyC2018 已提交
2687
### Implementation
C
CyC2018 已提交
2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701

设计不同种类的饮料,饮料可以添加配料,比如可以添加牛奶,并且支持动态添加新配料。每增加一种配料,该饮料的价格就会增加,要求计算一种饮料的价格。

下图表示在 DarkRoast 饮料上新增新添加 Mocha 配料,之后又添加了 Whip 配料。DarkRoast 被 Mocha 包裹,Mocha 又被 Whip 包裹。它们都继承自相同父类,都有 cost() 方法,外层类的 cost() 方法调用了内层类的 cost() 方法。

<div align="center"> <img src="../pics//c9cfd600-bc91-4f3a-9f99-b42f88a5bb24.jpg" width="600"/> </div><br>

```java
public interface Beverage {
    double cost();
}
```

```java
C
CyC2018 已提交
2702
public class DarkRoast implements Beverage {
C
CyC2018 已提交
2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754
    @Override
    public double cost() {
        return 1;
    }
}
```

```java
public class HouseBlend implements Beverage {
    @Override
    public double cost() {
        return 1;
    }
}
```

```java
public abstract class CondimentDecorator implements Beverage {
    protected Beverage beverage;
}
```

```java
public class Milk extends CondimentDecorator {

    public Milk(Beverage beverage) {
        this.beverage = beverage;
    }

    @Override
    public double cost() {
        return 1 + beverage.cost();
    }
}
```

```java
public class Mocha extends CondimentDecorator {

    public Mocha(Beverage beverage) {
        this.beverage = beverage;
    }

    @Override
    public double cost() {
        return 1 + beverage.cost();
    }
}
```

```java
public class Client {
C
CyC2018 已提交
2755

C
CyC2018 已提交
2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770
    public static void main(String[] args) {
        Beverage beverage = new HouseBlend();
        beverage = new Mocha(beverage);
        beverage = new Milk(beverage);
        System.out.println(beverage.cost());
    }
}
```

```html
3.0
```

### 设计原则

C
CyC2018 已提交
2771 2772 2773
类应该对扩展开放,对修改关闭:也就是添加新功能时不需要修改代码。饮料可以动态添加新的配料,而不需要去修改饮料的代码。

不可能把所有的类设计成都满足这一原则,应当把该原则应用于最有可能发生改变的地方。
C
CyC2018 已提交
2774

C
CyC2018 已提交
2775
### JDK
C
CyC2018 已提交
2776

C
CyC2018 已提交
2777 2778 2779 2780 2781
- java.io.BufferedInputStream(InputStream)
- java.io.DataInputStream(InputStream)
- java.io.BufferedOutputStream(OutputStream)
- java.util.zip.ZipOutputStream(OutputStream)
- java.util.Collections#checked[List|Map|Set|SortedSet|SortedMap]()
C
CyC2018 已提交
2782

C
CyC2018 已提交
2783 2784
## 5. 外观(Facade)

C
CyC2018 已提交
2785
### Intent
C
CyC2018 已提交
2786 2787 2788

提供了一个统一的接口,用来访问子系统中的一群接口,从而让子系统更容易使用。

C
CyC2018 已提交
2789
### Class Diagram
C
CyC2018 已提交
2790 2791 2792

<div align="center"> <img src="../pics//f9978fa6-9f49-4a0f-8540-02d269ac448f.png"/> </div><br>

C
CyC2018 已提交
2793
### Implementation
C
CyC2018 已提交
2794

C
CyC2018 已提交
2795
观看电影需要操作很多电器,使用外观模式实现一键看电影功能。
C
CyC2018 已提交
2796

C
CyC2018 已提交
2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
```java
public class SubSystem {
    public void turnOnTV() {
        System.out.println("turnOnTV()");
    }

    public void setCD(String cd) {
        System.out.println("setCD( " + cd + " )");
    }

    public void starWatching(){
        System.out.println("starWatching()");
    }
}
```

```java
public class Facade {
    private SubSystem subSystem = new SubSystem();

    public void watchMovie() {
        subSystem.turnOnTV();
        subSystem.setCD("a movie");
        subSystem.starWatching();
    }
}
```

```java
public class Client {
    public static void main(String[] args) {
        Facade facade = new Facade();
        facade.watchMovie();
    }
}
```

### 设计原则

C
CyC2018 已提交
2836
最少知识原则:只和你的密友谈话。也就是说客户对象所需要交互的对象应当尽可能少。
C
CyC2018 已提交
2837

C
CyC2018 已提交
2838
## 6. 享元(Flyweight)
C
CyC2018 已提交
2839

C
CyC2018 已提交
2840
### Intent
C
CyC2018 已提交
2841

C
CyC2018 已提交
2842 2843
利用共享的方式来支持大量细粒度的对象,这些对象一部分内部状态是相同的。

C
CyC2018 已提交
2844
### Class Diagram
C
CyC2018 已提交
2845 2846

- Flyweight:享元对象
C
CyC2018 已提交
2847 2848
- IntrinsicState:内部状态,享元对象共享内部状态
- ExtrinsicState:外部状态,每个享元对象的外部状态不同
C
CyC2018 已提交
2849 2850 2851

<div align="center"> <img src="../pics//d52270b4-9097-4667-9f18-f405fc661c99.png"/> </div><br>

C
CyC2018 已提交
2852
### Implementation
C
CyC2018 已提交
2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894

```java
public interface Flyweight {
    void doOperation(String extrinsicState);
}
```

```java
public class ConcreteFlyweight implements Flyweight {

    private String intrinsicState;

    public ConcreteFlyweight(String intrinsicState) {
        this.intrinsicState = intrinsicState;
    }

    @Override
    public void doOperation(String extrinsicState) {
        System.out.println("Object address: " + System.identityHashCode(this));
        System.out.println("IntrinsicState: " + intrinsicState);
        System.out.println("ExtrinsicState: " + extrinsicState);
    }
}
```

```java
public class FlyweightFactory {

    private HashMap<String, Flyweight> flyweights = new HashMap<>();

    Flyweight getFlyweight(String intrinsicState) {
        if (!flyweights.containsKey(intrinsicState)) {
            Flyweight flyweight = new ConcreteFlyweight(intrinsicState);
            flyweights.put(intrinsicState, flyweight);
        }
        return flyweights.get(intrinsicState);
    }
}
```

```java
public class Client {
C
CyC2018 已提交
2895

C
CyC2018 已提交
2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913
    public static void main(String[] args) {
        FlyweightFactory factory = new FlyweightFactory();
        Flyweight flyweight1 = factory.getFlyweight("aa");
        Flyweight flyweight2 = factory.getFlyweight("aa");
        flyweight1.doOperation("x");
        flyweight2.doOperation("y");
    }
}
```

```html
Object address: 1163157884
IntrinsicState: aa
ExtrinsicState: x
Object address: 1163157884
IntrinsicState: aa
ExtrinsicState: y
```
C
CyC2018 已提交
2914

C
CyC2018 已提交
2915
### JDK
C
CyC2018 已提交
2916

C
CyC2018 已提交
2917
Java 利用缓存来加速大量小对象的访问时间。
C
CyC2018 已提交
2918

C
CyC2018 已提交
2919 2920 2921 2922
- java.lang.Integer#valueOf(int)
- java.lang.Boolean#valueOf(boolean)
- java.lang.Byte#valueOf(byte)
- java.lang.Character#valueOf(char)
C
CyC2018 已提交
2923

C
CyC2018 已提交
2924
## 7. 代理(Proxy)
C
CyC2018 已提交
2925

C
CyC2018 已提交
2926
### Intent
C
CyC2018 已提交
2927

C
CyC2018 已提交
2928
控制对其它对象的访问。
C
CyC2018 已提交
2929

C
CyC2018 已提交
2930
### Class Diagram
C
CyC2018 已提交
2931 2932 2933 2934 2935 2936

代理有以下四类:

- 远程代理(Remote Proxy):控制对远程对象(不同地址空间)的访问,它负责将请求及其参数进行编码,并向不同地址空间中的对象发送已经编码的请求。
- 虚拟代理(Virtual Proxy):根据需要创建开销很大的对象,它可以缓存实体的附加信息,以便延迟对它的访问,例如在网站加载一个很大图片时,不能马上完成,可以用虚拟代理缓存图片的大小信息,然后生成一张临时图片代替原始图片。
- 保护代理(Protection Proxy):按权限控制对象的访问,它负责检查调用者是否具有实现一个请求所必须的访问权限。
C
CyC2018 已提交
2937
- 智能代理(Smart Reference):取代了简单的指针,它在访问对象时执行一些附加操作:记录对象的引用次数;当第一次引用一个持久化对象时,将它装入内存;在访问一个实际对象前,检查是否已经锁定了它,以确保其它对象不能改变它。
C
CyC2018 已提交
2938 2939 2940

<div align="center"> <img src="../pics//a6c20f60-5eba-427d-9413-352ada4b40fe.png"/> </div><br>

C
CyC2018 已提交
2941
### Implementation
C
CyC2018 已提交
2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020

以下是一个虚拟代理的实现,模拟了图片延迟加载的情况下使用与图片大小相等的临时内容去替换原始图片,直到图片加载完成才将图片显示出来。

```java
public interface Image {
    void showImage();
}
```

```java
public class HighResolutionImage implements Image {

    private URL imageURL;
    private long startTime;
    private int height;
    private int width;

    public int getHeight() {
        return height;
    }

    public int getWidth() {
        return width;
    }

    public HighResolutionImage(URL imageURL) {
        this.imageURL = imageURL;
        this.startTime = System.currentTimeMillis();
        this.width = 600;
        this.height = 600;
    }

    public boolean isLoad() {
        // 模拟图片加载,延迟 3s 加载完成
        long endTime = System.currentTimeMillis();
        return endTime - startTime > 3000;
    }

    @Override
    public void showImage() {
        System.out.println("Real Image: " + imageURL);
    }
}
```

```java
public class ImageProxy implements Image {
    private HighResolutionImage highResolutionImage;

    public ImageProxy(HighResolutionImage highResolutionImage) {
        this.highResolutionImage = highResolutionImage;
    }

    @Override
    public void showImage() {
        while (!highResolutionImage.isLoad()) {
            try {
                System.out.println("Temp Image: " + highResolutionImage.getWidth() + " " + highResolutionImage.getHeight());
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        highResolutionImage.showImage();
    }
}
```

```java
public class ImageViewer {
    public static void main(String[] args) throws Exception {
        String image = "http://image.jpg";
        URL url = new URL(image);
        HighResolutionImage highResolutionImage = new HighResolutionImage(url);
        ImageProxy imageProxy = new ImageProxy(highResolutionImage);
        imageProxy.showImage();
    }
}
```
C
CyC2018 已提交
3021

C
CyC2018 已提交
3022
### JDK
C
CyC2018 已提交
3023

C
CyC2018 已提交
3024 3025
- java.lang.reflect.Proxy
- RMI
C
CyC2018 已提交
3026

C
CyC2018 已提交
3027
# 参考资料
C
CyC2018 已提交
3028

C
CyC2018 已提交
3029
- 弗里曼. Head First 设计模式 [M]. 中国电力出版社, 2007.
C
CyC2018 已提交
3030 3031
- Gamma E. 设计模式: 可复用面向对象软件的基础 [M]. 机械工业出版社, 2007.
- Bloch J. Effective java[M]. Addison-Wesley Professional, 2017.
C
CyC2018 已提交
3032 3033 3034
- [Design Patterns](http://www.oodesign.com/)
- [Design patterns implemented in Java](http://java-design-patterns.com/)
- [The breakdown of design patterns in JDK](http://www.programering.com/a/MTNxAzMwATY.html)