-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGames.java
More file actions
76 lines (57 loc) · 1.46 KB
/
Games.java
File metadata and controls
76 lines (57 loc) · 1.46 KB
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
package innerclasses;
/**
* RUN:
* javac innerclasses/Games.java && java innerclasses.Games
* OUTPUT:
* Checkers move 0
* Checkers move 1
* Checkers move 2
* Chess move 0
* Chess move 1
* Chess move 2
* Chess move 3
*/
public class Games {
public static void playGame(GameFactory factory) {
Game g = factory.getGame();
while (g.move());
}
public static void main(String[] args) {
playGame(Checkers.factory);
playGame(Chess.factory);
}
}
interface Game {
boolean move();
}
interface GameFactory {
Game getGame();
}
class Checkers implements Game {
private Checkers() {}
private int moves = 0;
private static final int MOVES = 3;
public boolean move() {
System.out.println(getClass().getSimpleName() + " move " + moves);
return ++moves != MOVES;
}
public static GameFactory factory = new GameFactory() {
public Game getGame() {
return new Checkers();
}
};
}
class Chess implements Game {
private Chess() {}
private int moves = 0;
private static final int MOVES = 4;
public boolean move() {
System.out.println(getClass().getSimpleName() + " move " + moves);
return ++moves != MOVES;
}
public static GameFactory factory = new GameFactory() {
public Game getGame() {
return new Chess();
}
};
}