策略模式(Strategy Pattern)

整体的替换算法

1.基本介绍

无论什么程序,其目的都是为了解决问题,而为了解决问题,我们需要编写特定算法,使用策略模式可以整体的替换算法的实现部分,即算法的具体实现不依赖于业务类,将俩者分离开,降低耦合,可以很轻松使用不同算法,或者修改算法。


2.具体实例

Hand类:

手势类,被其他类调用,并非设计模式中角色。

public class Hand {
	public static final int HANDVALUE_GUU = 0; // 表示石头的值
	public static final int HANDVALUE_CHO = 1;// 表示剪刀的值
	public static final int HANDVALUE_PAA = 2;// 表示布的值
	public static final Hand[] hand = { // 表示猜拳中手势所对应的字符串
			new Hand(HANDVALUE_GUU), new Hand(HANDVALUE_CHO), new Hand(HANDVALUE_PAA)
	};
	private static final String[] name = { // 猜拳中所代表的字符串
			"石头", "剪刀", "布" };
	private int handValue; // 猜拳中手势所对应的值
	private Hand(int handValue) {
		this.handValue = handValue;
	}

	public static Hand getHand(int handValue) { // 根据手势的值获得对应实例
		return hand[handValue];

	}
	public boolean isStrongThan(Hand h) { // 如果this胜了h则返回true
		return fight(h) == 1;
	}

	public boolean isWeakerThan(Hand h) { // 如果this输了h则返回true
		return fight(h) == -1;
	}

	private int fight(Hand h) { // 计分,平 0,胜1,负-1
		if (this == h) {
			return 0;
		} else if ((this.handValue + 1) % 3 == h.handValue) {
			return 1;
		} else {
			return -1;
		}
	}

	public String toString() {
		return name[handValue];
	}
}

Strategy接口

定义了猜拳策略的抽象方法接口,具体有子类去实现算法。

/**
 * @author Jay
 * @date 2019/7/6 21:43
 * @description
 */
public interface Strategy {
    void study(boolean win);
    Hand nextHand();
}

具体算法

public class WinningStrategy implements Strategy {
	private Random random;
	private boolean won = false;
	private Hand preHand;
	public WinningStrategy() {
		random = new Random();
	}
	@Override
	public Hand nextHand() {
		
		if(!won) {
			preHand =Hand.getHand(random.nextInt(3));
		}		
		return preHand;
	}
	@Override
	public void study(boolean win) {
		won =win;
	}
}
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() {
		random = new Random();
	}

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

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

	@Override
	public void study(boolean win) {
		if (win) {
			history[prevHandValue][currentHandValue]++;
		} else {
			history[prevHandValue][(currentHandValue + 1) % 3]++;
			history[prevHandValue][(currentHandValue + 2) % 3]++;
		}

	}

}

Player类

表示猜拳游戏选手的类,也就是调用算法结果去具体应用的类.

/**
 * @author Jay
 * @date 2019/7/6 21:44
 * @description
 */
public class Player {
    private String name;
    private Strategy strategy;
    private int wincount;
    private int losecount;
    private int gamecount;

    public Player(String name, Strategy strategy) { // 赋予姓名和策略
        super();
        this.name = name;
        this.strategy = strategy;
    }

    public Hand nextHand() {
        //调用接口的静态获取方法,也就是说,将本类要来生成的实例,委托给接口去实现,这种弱关联关系即为委托关系
        //接口可以调用其具体的实现类,从而返回不同的具体实例,方便整体的替换,降低程序的耦合性.
        return strategy.nextHand(); // 策略决定下一局要出的手势,接口类型,不论以后算法如何修改对于此类没有影响

    }

    public void win() {
        strategy.study(true);
        wincount++;
        gamecount++;
    }

    public void lose() {
        strategy.study(false);
        losecount++;
        gamecount++;
    }

    public void even() {
        gamecount++;
    }

    @Override
    public String toString() {
        return "[" + name + ":" + gamecount + "  局游戏  " + wincount + " 胜  " + losecount + " 负 " + "]";
    }
}

main

/**
 * @author Jay
 * @date 2019/7/6 21:45
 * @description
 */
public class Main {
    public static void main(String[] args) {
        Player p1 = new Player("张三", new WinningStrategy());//不同的策略更换对于程序没有影响
        Player p2 = new Player("李四", new ProbStrategy());
        for (int i = 0; i < 10000; i++) {
            Hand nextHand1 = p1.nextHand();
            Hand nextHand2 = p2.nextHand();
            if (nextHand1.isStrongThan(nextHand2)) {
                System.out.println("Winner:" + p1);
                p1.win();
                p2.lose();
            } else if (nextHand1.isWeakerThan(nextHand2)) {
                System.out.println("Winner:" + p2);
                p1.lose();
                p2.win();
            } else {
                System.out.println("平局...");
                p1.even();
                p2.even();
            }
        }
    }
}

3.模式具体角色

Strategy(策略)

负责决定实现策略所必需的接口。

ConcreteStrategy(具体的策略)

具体实现接口,具体实现所用的算法。

Context(上下文)

负责使用Strategy角色,Strategy为接口类型,所以其所有实现类都可替换。


4.编写Strategy

编写算法时有时会写在具体方法中,而策略模式将算法部分与其他部分分离出来,只是定义了与算法相关的接口,然后在程序中以委托的方式来使用。

当我们修改算法时,不需要去修改具体方法,只需去修改具体实现接口的方法即可,实现了弱耦合,而且,使用委托这种弱关联关系可以很方便的整体替换算法。


To GitHub

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值