美文网首页
论策略模式

论策略模式

作者: 行走的鸡汤哥 | 来源:发表于2019-04-02 22:45 被阅读0次

    策略模式的定义

    策略模式的定义:(引用百度百科的对策略模式的简介

    策略模式作为一种软件设计模式,指对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。比如每个人都要“交个人所得税”,但是“在美国交个人所得税”和“在中国交个人所得税”就有不同的算税方法。

    单薄的示例

    百度百科的描述表达了策略模式的核心思想。网上很多对策略模式的介绍也都体现了该思想,但我觉得他们举得例子都不能完美展现出策略模式的真正用途。

    以百度百科策略模式的示例为例:

    百度百科-策略模式代码示例

    上述示例先构建了一个出行策略的接口,再实现了三个具体的策略,最后调用不同的具体策略实现,达到了策略切换的效果。
    此示例虽然体现了策略模式的核心思想,但太单薄了,用多态的特性来解释也是很合适的。

    充分体现策略模式的场景

    我觉得最能体现策略模式的场景,应该是存在多种策略,每种策略有多种实现算法,策略与策略间有组合关系,如《Head First 设计模式》中对策略模式的讲解。

    /**
     * 机动模式
     */
    public interface ActionModel {
        String action();
    }
    
    /**
     * 具体机动模式:飞行
     */
    public class Flying implements ActionModel {
        @Override
        public String action() {
            return "飞行模式";
        }
    }
    
    /**
     * 具体机动模式:航行
     */
    public class Sailing implements ActionModel {
        @Override
        public String action() {
            return "航行模式";
        }
    }
    
    /**
     * 攻击模式
     */
    public interface AttackModel {
        String attack();
    }
    
    /**
     * 具体攻击模式:轰炸
     */
    public class Bomb implements AttackModel {
        @Override
        public String attack() {
            return "轰炸模式";
        }
    }
    
    /**
     * 具体攻击模式:狙击
     */
    public class Snipe implements AttackModel {
        @Override
        public String attack() {
            return "狙击模式";
        }
    }
    
    /**
     * 模式使用者
     */
    @Data
    @AllArgsConstructor
    public class Robot {
        private String name;
        private ActionModel action;
        private AttackModel attack;
    
        public void describe() {
            System.out.println("I'm auto robot " + name + "! 行动模式为:" + action.action() + ";攻击模式为:" + attack.attack());
        }
    }
    
    // 策略模式使用示例
    public class Demo {
        public static void main(String[] args) {
            ActionModel fly = new Flying();
            ActionModel sail = new Sailing();
    
            AttackModel snipe = new Snipe();
            AttackModel bomb = new Bomb();
    
            Robot optimusPrime = new Robot("Optimus prime", fly, snipe);
            optimusPrime.describe();
            Robot bumblebee = new Robot("Bumblebee", fly, bomb);
            bumblebee.describe();
            Robot Decepticon = new Robot("Decepticon", sail, bomb);
            Decepticon.describe();
        }
    }
    

    上述示例通过切换机动模式、攻击模式或其他更多模式,能组合出各种不同的机器人,充分体现了策略模式的意义。

    相关文章

      网友评论

          本文标题:论策略模式

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