60 lines
1.3 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// interfaces/Games.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// A Game framework using Factory Methods
2015-06-15 17:47:35 -07:00
interface Game { boolean move(); }
interface GameFactory { Game getGame(); }
class Checkers implements Game {
private int moves = 0;
private static final int MOVES = 3;
@Override
public boolean move() {
2015-11-03 12:00:44 -08:00
System.out.println("Checkers move " + moves);
2015-06-15 17:47:35 -07:00
return ++moves != MOVES;
}
}
class CheckersFactory implements GameFactory {
@Override
public Game getGame() { return new Checkers(); }
}
class Chess implements Game {
private int moves = 0;
private static final int MOVES = 4;
@Override
public boolean move() {
2015-11-03 12:00:44 -08:00
System.out.println("Chess move " + moves);
2015-06-15 17:47:35 -07:00
return ++moves != MOVES;
}
}
class ChessFactory implements GameFactory {
@Override
public Game getGame() { return new Chess(); }
}
public class Games {
public static void playGame(GameFactory factory) {
Game s = factory.getGame();
while(s.move())
;
}
public static void main(String[] args) {
playGame(new CheckersFactory());
playGame(new ChessFactory());
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Checkers move 0
Checkers move 1
Checkers move 2
Chess move 0
Chess move 1
Chess move 2
Chess move 3
2015-09-07 11:44:36 -06:00
*/