策略模式是一个很easy的模式。
它定义一系列的算法,把它们一个个封装起来,而且使它们能够相互替换。
考虑到我在做一个剪刀石头布的游戏,能够和计算机对战。
计算机的难度等级分为2个等级:普通难度和无法战胜难度。
普通难度是指电脑会随机出石头、剪刀、布。而无法战胜难度是指电脑会“作弊”。电脑会事先知道玩家出的是什么手势。
假设玩家出的是剪刀。那么电脑会出石头,玩家永远的无法取胜。
那么,这两个难度分别代表两种算法,为了使得它们可以被游戏的主类装载,它们都应该继承于同一个接口或类。并暴露出电脑出手势的方法,代码例如以下:
import java.util.Random;
import java.util.Scanner;
interface GameStrategy{
int play(int player);
}
class FingerGuessing{
Scanner playerScanner = new Scanner(System.in);
public String toString(int finger){
switch (finger){
case 1:
return "石头";
case 2:
return "剪刀";
case 3:
return "布";
default:
return "错误!";
}
}
public void start(GameStrategy comStrategy){
boolean gameOver = false;
while (!gameOver){
System.out.println("请出拳(按回车确认):1、石头;2、剪刀。3、布");
int playerChoice = 0;
while ( playerChoice <= 0 || playerChoice > 4){
playerChoice = playerScanner.nextInt();
}
int comChoice = comStrategy.play(playerChoice);
System.out.printf("你出的是%s。计算机出的是%s\n", toString(playerChoice), toString(comChoice));
if (playerChoice == comChoice){
System.out.println("平局");
} else if (playerChoice + 1 == comChoice || playerChoice - 2 == comChoice){
System.out.println("恭喜你获胜了!");
gameOver = true;
} else {
System.out.println("非常遗憾你失败了!");
gameOver = true;
}
}
}
}
class Normal implements GameStrategy{
public int play(int player) {
Random rnd = new Random();
return rnd.nextInt(3) + 1;
}
}
class Hard implements GameStrategy{
public int play(int player) {
switch (player){
case 1:
return 3;
case 2:
return 1;
case 3:
return 2;
default:
return 1;
}
}
}
public class Strategy
{
public static void main(String[] args) {
FingerGuessing guess = new FingerGuessing();
System.out.println("一般难度:");
guess.start(new Normal());
System.out.println("你不可能获胜的难度:");
guess.start(new Hard());
}
电脑的出手势方式继承于GameStrategy接口。play方法返回的是电脑出的手势(石头、剪刀、布),传入的參数player是玩家出的手势(用于无法展示难度中作弊)。在游戏类中,start方法接受一个满足GameStrategy接口的对象,也就是相当于它接受不同的算法。在main方法中。我们传入了一个普通难度的算法,以及一个无法战胜难度的算法,大家能够试着执行一下。
另外,这个模式的长处是,如果要设计一种新的难度,十分方便,仅仅要设计一个继承于GameStrategy的类。并在play方法中编写自己的算法就可以。