-
Notifications
You must be signed in to change notification settings - Fork 1
/
Template.java
71 lines (59 loc) · 1.43 KB
/
Template.java
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
// Template pattern - example models a board game between two players
package behavioral.template;
abstract class Game
{
public Game(int numberOfPlayers) {
this.numberOfPlayers = numberOfPlayers;
}
// Notice this is not abstract, so all inheritors have the same implementation
public void run()
{
start();
while(!haveWinner())
takeTurn();
System.out.println("Player " + getWinningPlayer()
+ " wins");
}
protected abstract int getWinningPlayer();
protected abstract void takeTurn();
protected abstract boolean haveWinner();
protected abstract void start();
protected int currentPlayer;
protected final int numberOfPlayers;
}
class Chess extends Game
{
private int maxTurns = 10;
private int turn = 1;
public Chess()
{
super(2);
}
@Override
protected int getWinningPlayer()
{
return 0;
}
@Override
protected void takeTurn()
{
System.out.println("Turn " + (turn++)
+ " taken by player " + currentPlayer);
currentPlayer = (currentPlayer+1) % numberOfPlayers;
}
@Override
protected boolean haveWinner() {
return turn == maxTurns;
}
@Override
protected void start()
{
System.out.println("Starting a game of chess.");
}
}
class TemplateDemo
{
public static void main(String[] args) {
new Chess().run();
}
}