-
Notifications
You must be signed in to change notification settings - Fork 0
/
TemplateMethod.cs
112 lines (83 loc) · 2.58 KB
/
TemplateMethod.cs
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/**
* An abstract class that is common to several games in
* which players play against the others, but only one is
* playing at a given time.
*/
namespace Design_Patterns
{
class TemplateMethodPattern
{
internal abstract class GameObject
{
protected int PlayersCount;
abstract protected bool EndOfGame();
abstract protected void InitializeGame();
abstract protected void MakePlay(int player);
abstract protected void PrintWinner();
/* A template method : */
public void PlayOneGame(int playersCount)
{
PlayersCount = playersCount;
InitializeGame();
var j = 0;
while (!EndOfGame())
{
MakePlay(j);
j = (j + 1) % playersCount;
}
PrintWinner();
}
}
//Now we can extend this class in order to implement actual games:
public class Monopoly : GameObject
{
/* Implementation of necessary concrete methods */
protected override void InitializeGame()
{
// Initialize money
}
protected override void MakePlay(int player)
{
// Process one turn of player
}
protected override bool EndOfGame()
{
return true;
}
protected override void PrintWinner()
{
// Display who won
}
/* Specific declarations for the Monopoly game. */
// ...
}
public class Chess : GameObject
{
/* Implementation of necessary concrete methods */
protected override void InitializeGame()
{
// Put the pieces on the board
}
protected override void MakePlay(int player)
{
// Process a turn for the player
}
protected override bool EndOfGame()
{
return true;
// Return true if in Checkmate or Stalemate has been reached
}
protected override void PrintWinner()
{
// Display the winning player
}
/* Specific declarations for the chess game. */
// ...
}
public static void Test()
{
GameObject game = new Monopoly();
game.PlayOneGame(2);
}
}
}