美文网首页
策略模式

策略模式

作者: 星星_点灯 | 来源:发表于2018-05-10 15:27 被阅读11次

    什么是策略模式?

    策略模式属于对象的行为模式。其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。

    策略模式的结构

    策略模式是对算法的包装,是把使用算法的责任和算法本身分开来,委派给不同的对象管理;
    策略模式有三个角色:
    环境角色(Context):持有一个Strategy的引用
    抽象策略角色(Strategy):这是一个抽象角色,通常由一个接口或抽象类来实现,此角色给出所有具体策略类所需的接口;
    具体策略角色(ConcreteStrategy):包装了相关的算法或行为,实现了抽象策略角色的接口;

    UML图如下所示:


    策略模式UML图

    策略模式的应用场景

    1、针对同一类型问题的多种处理方式,仅仅是具体行为有差别时;
    2、需要安全的封装多种同一类型操作时;
    3、出现同一抽象类有多个子类,使用if else或switch case来选择具体子类时;

    举个例子,有这样一个场景,我们在买lol的皮肤时,会对不同的会员有不同的折扣,比如对普通会员是9折,超级会员是8折、黄金会员7折、白金会员5折等等;这时,我们要根据不同的会员,计算出要购买的皮肤的价格;

    抽象策略角色:Strategy,提取具体策略角色要实现的方法,计算实际要付的价格;

    public interface DiscountStrategy {
    
        double discountPrice(double price);//计算折扣价
    
    }
    

    具体策略角色
    普通会员

    public class CommonDiscount implements DiscountStrategy {
        @Override
        public double discountPrice(double price) {
            return price * 0.9;//普通会员9折优惠
        }
    }
    

    超级会员

    public class SuperDiscount implements DiscountStrategy {
        @Override
        public double discountPrice(double price) {
            return price * 0.8;//超级会员8折优惠
        }
    }
    

    黄金会员

    public class GoldDiscount implements DiscountStrategy {
        @Override
        public double discountPrice(double price) {
            return price * 0.7;//黄金会员7折优惠
        }
    }
    

    白金会员

    public class PlatinumDiscount implements DiscountStrategy {
        @Override
        public double discountPrice(double price) {
            return price * 0.5;//白金会员5折优惠
        }
    }
    

    环境角色

    public class Price {
        private DiscountStrategy strategy;//持有一个具体的策略对象
    
    
        public void setStrategy(DiscountStrategy strategy) {//设置策略
            this.strategy = strategy;
        }
    
        public double getPrice(double price) {//计算最终价格
            return strategy.discountPrice(price);
        }
    }
    

    主程序使用:

            Price price = new Price();
            price.setStrategy(new CommonDiscount());
            System.out.println("普通会员的价格:" + price.getPrice(100.0));
            price.setStrategy(new SuperDiscount());
            System.out.println("超级会员的价格:" + price.getPrice(100.0));
            price.setStrategy(new GoldDiscount());
            System.out.println("黄金会员的价格:" + price.getPrice(100.0));
            price.setStrategy(new PlatinumDiscount());
            System.out.println("白金会员的价格:" + price.getPrice(100.0));
    

    运行结果:


    运行结果

    以上举了一个简单粗暴的例子,计算不同会员不同的折扣价,但是这也太简单了,在实际的开发场景中,我们还要具体区分会员的等级,而又应该如何区分呢?所以,上例我们只是简单的介绍了一些策略模式的原理,接下来我们来进行真实的开发场景分析,还是以上述会员为例,玩过腾讯游戏的都知道,我们不停的充扣币,买礼包,买装备,每充一次,都会有相应的积分,当积分到底固定值后,会员等级就会提升;所以我们就以此为例,到达1000积分为普通会员、2000超级会员、3000黄金会员、5000白金会员;所以,我们现在要新建一个环境角色类 Player:

    public class Player {
        private double totalMoney = 0;//总计消费
        private double money = 0;//单次消费金额
        private DiscountStrategy strategy = new OriginalDiscount();//默认的折扣方式 不打折 原价
    
        public double buy(double price) {//根据消费金额,返回相应的折扣
            this.money = price;
            totalMoney += price;
    
            if (totalMoney >= 5000) {//白金会员
                strategy = new PlatinumDiscount();
            } else if (totalMoney >= 3000) {//黄金会员
                strategy = new GoldDiscount();
            } else if (totalMoney >= 2000) {//超级会员
                strategy = new SuperDiscount();
            } else if (totalMoney >= 1000) {//普通会员
                strategy = new CommonDiscount();
            }
    
            return strategy.discountPrice(price);
        }
    }
    

    主程序中使用:

    Player player1 = new Player();//玩家1
    System.out.println("玩家1的商品原价是:1000  折扣价为:" + player1.buy(1000));
    Player player2 = new Player();//玩家2
    System.out.println("玩家2的商品原价是:2000  折扣价为:" + player1.buy(2000));
    Player player3 = new Player();//玩家3
    System.out.println("玩家3的商品原价是:5000  折扣价为:" + player1.buy(5000));
    

    运行结果:


    运行结果

    在上面的基础上,我们引入简单工厂来进行优化,新建一个简单的折扣工厂类:

    public class DisCountFactory {
        private DisCountFactory() {
        }
    
        public static DiscountStrategy createDiscount(double totalMoney) {
            if (totalMoney >= 5000) {//白金会员
                return new PlatinumDiscount();
            } else if (totalMoney >= 3000) {//黄金会员
                return new GoldDiscount();
            } else if (totalMoney >= 2000) {//超级会员
                return new SuperDiscount();
            } else if (totalMoney >= 1000) {//普通会员
                return new CommonDiscount();
            }
    
            return new OriginalDiscount();//非会员
        }
    }
    

    然后再修改Player类:

    public class Player {
        private double totalMoney = 0;//总计消费
        private double money = 0;//单次消费金额
        private DiscountStrategy strategy = new OriginalDiscount();//默认的折扣方式 不打折 原价
    
        public double buy(double price) {//根据消费金额,返回相应的折扣
            this.money = price;
            totalMoney += price;
            strategy = DisCountFactory.createDiscount(totalMoney);
            return strategy.discountPrice(price);
        }
    }
    

    这样一个简单工厂+策略模式的需求就完成了,这样做得好处是将制定策略的功能从玩家类里分离出来了,更便于我们控制和管理;

    策略模式的优缺点

    优点:
    1、策略模式提供了管理相关算法组的办法,策略类的等级结构定义了一个算法组或行为组,恰当的使用继承,可以把公共代码移到父类里面,避免代码重复;
    2、策略模式可以避免使用过多的if else判断,更易于维护;
    缺点:
    1、客户端必须知道所有的策略类,并自行决定使用哪个策略类,因此策略模式只适用于客户端已知的算法和行为的情况,有使用局限性;
    2、由于策略模式把每个具体的策略实现都单独封装成为类,如果备选的策略很多的话,创建的对象类会过多;

    相关文章

      网友评论

          本文标题:策略模式

          本文链接:https://www.haomeiwen.com/subject/ajzblftx.html