0%

设计模式-模板方法模式

一个抽象类公开定义了执行它的方法的方式/模板。它的子类可以按需要重写方法实现,但调用将以抽象类中定义的方式进行
定义一个操作中的算法的骨架,而将一些步骤延迟到子类中
把不变的部分移至父类, 去除子类重复代码

示例

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public abstract class Game 
{
public abstract void initialize();
public abstract void startPlay();
public abstract void endPlay();

//模板
public void play(){

//初始化游戏
initialize();

//开始游戏
startPlay();

//结束游戏
endPlay();
}
}
public class Cricket : Game
{

public override void endPlay() {
Console.WriteLine("Cricket Game Finished!");
}

public override void initialize() {
Console.WriteLine("Cricket Game Initialized! Start playing.");
}

public override void startPlay() {
Console.WriteLine("Cricket Game Started. Enjoy the game!");
}
}
public class Football : Game
{

public override void endPlay() {
Console.WriteLine("Football Game Finished!");
}

public override void initialize() {
Console.WriteLine("Football Game Initialized! Start playing.");
}

public override void startPlay() {
Console.WriteLine("Football Game Started. Enjoy the game!");
}
}
Game game = new Cricket();
game.play();
System.out.println();
game = new Football();
game.play();