`

策略模式

阅读更多
策略模式可以更换实现算法的部分而且不留痕迹,切换整个算法,简化改为采用其他方法来解决同样的问题,在设计程序时,比较习惯把实现算法这部分结合到方法里面,但是策略模式则故意把算法的部分跟其他部分分开,只规定跟算法有关的接口部分,然后再从程序这边以委托的方式来利用运算法则,因为有了委托关系,所以才能切换算法,尤其是机动性的切换动作
package com.tools.pattern.strategy;
public class Hand {

// 石头的值
private static final int HANDVALUE_GUU = 0;

// 剪刀的值
private static final int HANDVALUE_CHO = 1;

// 布的值
private static final int HANDVALUE_PAA = 2;

private static final Hand[] hands = { new Hand(HANDVALUE_GUU),
new Hand(HANDVALUE_CHO), new Hand(HANDVALUE_PAA) };

private static final String[] names = { "石头", "剪刀", "布" };
private int handValue;

private Hand(int handValue) {
this.handValue = handValue;
}

public static Hand getHand(int handValue) {
return hands[handValue];
}

public boolean isStrongerThan(Hand h) {
return 1 == this.fight(h);
}

public boolean isWeakerThan(Hand h) {
return -1 == this.fight(h);
}

private int fight(Hand h) {
if (this == h) {
return 0;
} else if ((this.handValue + 1) % 3 == h.handValue) {
return 1;
} else {
return -1;
}
}

public String toString() {
return names[this.handValue];
}
}

package com.tools.pattern.strategy;
public interface Strategy {

Hand nexHand();

void study(boolean isWin);
}

package com.tools.pattern.strategy;
import java.util.Random;
public class WinningStrategy implements Strategy {

private Random random;
private Hand preHand;
private boolean isWon = false;

public WinningStrategy(int seed) {
random = new Random(seed);
}

public Hand nexHand() {
if (!this.isWon) {
preHand = Hand.getHand(random.nextInt(3));
}
return preHand;
}

public void study(boolean isWin) {
this.isWon = isWin;
}
}

package com.tools.pattern.strategy;
import java.util.Random;
public class ProbStrategy implements Strategy {

private Random random;
private int prevHandValue = 0;
private int currentHandValue = 0;
private int[][] history = { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } };

public ProbStrategy(int seed) {
random = new Random(seed);
}

private int getSum(int hv) {
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += history[hv][i];
}
return sum;
}

public Hand nexHand() {
int bet = random.nextInt(this.getSum(this.currentHandValue));
int handValue = 0;
if (bet < history[this.currentHandValue][0]) {
handValue = 0;
} else if (bet < history[this.currentHandValue][0]
+ history[this.currentHandValue][1]) {
handValue = 1;
} else {
handValue = 2;
}
this.prevHandValue = this.currentHandValue;
this.currentHandValue = handValue;
return Hand.getHand(handValue);
}

public void study(boolean isWin) {
if (isWin) {
history[this.prevHandValue][this.currentHandValue]++;
} else {
history[this.prevHandValue][(this.currentHandValue + 1) % 3]++;
history[this.prevHandValue][(this.currentHandValue + 2) % 3]++;
}
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics