⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 games17.java

📁 JAVA编程思想第四版英文原版习题答案. pdf原版的
💻 JAVA
字号:
// innerclasses/Games17.java
// TIJ4 Chapter Innerclasses, Exercise 17, page 364
/* Modify the solution to Exercise 19 from the Interfaces chapter to use
* anonymous inner classes. 
* (Exercise 19, Interfaces: Create a framework using Factory Methods
* that performs both coin tossing and dice tossing.
*/
import java.util.*;
import static org.greggordon.tools.Print.*;

interface Games {
	void play();
}

interface GamesFactory {
	Games getGames();
}

class CoinToss implements Games {
	Random rand = new Random();
	public void play() { 
		print("Toss Coin: ");
		switch(rand.nextInt(2)) {
			case 0 : println("Heads"); return;
			case 1 : println("Tails"); return;
			default: println("OnEdge"); return;
		} 
	}
	public static GamesFactory factory =
		new GamesFactory() {
			public Games getGames() { return new CoinToss(); }	
		};
}

class DiceThrow implements Games {
	Random rand = new Random();
	public void play() { 
		print("Throw Dice: " + (rand.nextInt(6) + 1));		
	}
	public static GamesFactory factory =
		new GamesFactory() {
			public Games getGames() { return new DiceThrow(); }
		};
}

public class Games17 {
	public static void playGame(GamesFactory factory) {
		Games g = factory.getGames();
		g.play();
	}
	public static void main(String [] args) {
		playGame(CoinToss.factory);
		playGame(DiceThrow.factory);			
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -