模板模式

在模板模式(Template Pattern)中,一个抽象类公开定义了执行它的方法的方式/模板。它的子类可以按需要重写方法实现,但调用将以抽象类中定义的方式进行

Class Diagram

Implemenation

模板类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public abstract class Game {
abstract void initialize();

abstract void startPlay();

abstract void endPlay();

//模板
public final void play() {

//初始化游戏
initialize();

//开始游戏
startPlay();

//结束游戏
endPlay();
}
}

模板实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Football extends Game {

@Override
void endPlay() {
System.out.println("Football Game Finished!");
}

@Override
void initialize() {
System.out.println("Football Game Initialized! Start playing.");
}

@Override
void startPlay() {
System.out.println("Football Game Started. Enjoy the game!");
}
}

// ====================================

public class Cricket extends Game {

@Override
void endPlay() {
System.out.println("Cricket Game Finished!");
}

@Override
void initialize() {
System.out.println("Cricket Game Initialized! Start playing.");
}

@Override
void startPlay() {
System.out.println("Cricket Game Started. Enjoy the game!");
}
}

测试类

1
2
3
4
5
6
7
8
9
10
public class TemplateTest {
@Test
public void test() throws Exception{
Game game = new Cricket();
game.play();
System.out.println();
game = new Football();
game.play();
}
}

Example

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

Refence