Skip to content

Commit

Permalink
添加模板方法模式
Browse files Browse the repository at this point in the history
  • Loading branch information
VentureQ committed Jul 11, 2021
1 parent 51aaf60 commit 598fde9
Showing 1 changed file with 98 additions and 0 deletions.
98 changes: 98 additions & 0 deletions 23种设计模式/模板方法模式的概念及Java实现.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
### Intent

定义算法框架,并将一些步骤的实现延迟到子类。

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

### Class Diagram

<img src="https://gitee.com/venture_git/PicGo-CloudImg/raw/master/img/20210711135849.png" alt="img" style="zoom:67%;" />

### Implementation

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

<img src="https://gitee.com/venture_git/PicGo-CloudImg/raw/master/img/20210711135916.png" alt="img" style="zoom:67%;" />

```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
public class Coffee extends CaffeineBeverage {
@Override
void brew() {
System.out.println("Coffee.brew");
}

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

```java
public class Tea extends CaffeineBeverage {
@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
```

### JDK

- java.util.Collections#sort()
- java.io.InputStream#skip()
- java.io.InputStream#read()
- java.util.AbstractList#indexOf()

0 comments on commit 598fde9

Please sign in to comment.