策略模式

一.策略模式

策略模式:根据不同选择,进行不同算法切换

二.策略模式-示例

以游戏中的段位匹配进行示例展示-比如青铜的只能匹配青铜到白银,等

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.策略类过多,增加维护难度

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值