July 7, 2008
at
Monday, July 07, 2008
Labels:
Computer Science,
Java,
Thinking in Java
Posted by
Billy
Chapter: Interfaces
Create a framework using Factory Methods that performs both coin tossing and dice tossing.
In Java:
package chapter.interfaces;
import java.util.*;
interface Game {
int toss();
}
interface GameFactory {
Game getGame();
}
class Dice implements Game {
public int toss() {
Random rand = new Random(55);
return rand.nextInt(7);
}
}
class DiceFactory implements GameFactory {
public Game getGame() {
return new Dice();
}
}
class Coins implements Game {
public int toss() {
Random rand = new Random(55);
return rand.nextInt(3);
}
}
class CoinsFactory implements GameFactory {
public Game getGame() {
return new Coins();
}
}
public class Exercise19 {
public static void playGame(GameFactory factory) {
Game game = factory.getGame();
for (int i = 0; i < 8; i++)
System.out.println(game.toss());
}
public static void main(String[] args) {
playGame(new CoinsFactory());
playGame(new DiceFactory());
}
}
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment