一.策略模式
策略模式:根据不同选择,进行不同算法切换
二.策略模式-示例
以游戏中的段位匹配进行示例展示-比如青铜的只能匹配青铜到白银,等
1.不采用策略模式写法
public class Test {
public static void main(String[] args) {
String level = "青铜";
int num = 4;
if("青铜".equals(level)){
System.out.println("匹配"+num+"名,青铜到白银段位玩家!");
}else if("白银".equals(level)){
System.out.println("匹配"+num+"名,青铜到黄金段位玩家!");
}else if ("黄金".equals(level)){
System.out.println("匹配"+num+"名,白银到铂金段位玩家!");
}else if ("铂金".equals(level)){
System.out.println("匹配"+num+"名,黄金到钻石段位玩家!");
}//.....
}
}
2.采用策略模式写法
1.创建匹配接口 IMatching
public interface IMatching {
public String match(int num);
}
2.创建,青铜,白银,黄金,铂金,钻石段位的匹配策略
public class BronzeLevel implements IMatching {
@Override
public String match(int num) {
return "匹配"+num+"名,青铜到白银段位玩家!";
}
}
public class SilverLevel implements IMatching {
@Override
public String match(int num) {
return "匹配"+num+"名,青铜到黄金段位玩家!";
}
}
public class GoldLevel implements IMatching {
@Override
public String match(int num) {
return "匹配"+num+"名,白银到白金段位玩家!";
}
}
public class PlatinumLevel implements IMatching {
@Override
public String match(int num) {
return "匹配"+num+"名,黄金到钻石段位玩家!";
}
}
public class DiamondLevel implements IMatching {
@Override
public String match(int num) {
return "匹配"+num+"名,白金到钻石段位玩家!";
}
}
3.创建匹配上下文,负责与匹配策略进行交互
public class MatchContext {
private IMatching iMatching;
public MatchContext(IMatching iMatching) {
this.iMatching = iMatching;
}
public String startMatch(int num){
return iMatching.match(num);
}
}
4.创建一个测试类,进行测试
public class Test {
public static void main(String[] args) {
int num = 4;
System.out.println(new MatchContext(new BronzeLevel()).startMatch(num));
System.out.println(new MatchContext(new SilverLevel()).startMatch(num));
System.out.println(new MatchContext(new DiamondLevel()).startMatch(num));
}
}
5.测试结果
6.UML
三.策略模式优缺点
优点:
1.复合开闭原则,当我们需要新增一中策略时,只需要实现IMatching接口,去实现里面的方法就行
2.避免使用多重if...else...语句
缺点:
1.客户端必须知道所有策略,并决定使用哪一个策略
2.策略类过多,增加维护难度