• java设计模式之策略模式


    策略模式

         定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户(大话设计模式)。

    策略模式UML图

          

    策略模式代码

       古代的各种计谋都是一种策略,这次我们的例子就拿其中一种离间计来写的,理解起来非常容易,代码如下:

    package com.roc.strategy;
    /**
     * 这是一个策略
     * @author liaowp
     *
     */
    public interface StrategyInterface {
            /**
             * 执行方法
             */
            public void excit();
    }
    package com.roc.strategy;
    /**
     * 具体的策略<离间计>
     * @author liaowp
     *
     */
    public class DetailStrategy implements StrategyInterface{
    
        /**
         * 具体策略
         */
        public void excit() {
            System.out.println("hi gay,给你个离间计");
        }
    
    }
    package com.roc.strategy;
    /**
     * 使用离间计的地方
     * @author liaowp
     *
     */
    public class UserStategy {
        private StrategyInterface strategyInterface;
        
        public UserStategy(StrategyInterface strategyInterface){
            this.strategyInterface=strategyInterface;
        }
        
        public void action(){
            this.strategyInterface.excit();
        }
    }
    package com.roc.strategy;
    /**
     * 主场景    策略模式
     * @author liaowp
     *
     */
    public class Client {
            public static void main(String[] args) {
                System.out.println("离间计干死你");
                UserStategy stategy;
                stategy=new UserStategy(new DetailStrategy());
                stategy.action();
                System.out.println("离间成功");
            }
    }

    策略模式适用场景

    • 几个类的主要逻辑相同,只在部分逻辑的算法和行为上稍有区别的情况。
    • 有几种相似的行为,或者说算法,客户端需要动态地决定使用哪一种,那么可以使用策略模式,将这些算法封装起来供客户端调用。

         

  • 相关阅读:
    tableView
    ios设计模式 设计一个应用程序 笔记
    Touching the Background to close the Keyboard
    fdfd
    fdffafadf
    Declaring the Action Method
    网易公开课IOS笔记 第二课
    getters and setters
    objective c
    Google编码规范 C++ Style Guide, JavaScript Style Guide, ObjectiveC Style Guide, and Python Style Guide
  • 原文地址:https://www.cnblogs.com/liaoweipeng/p/5791058.html
Copyright © 2020-2023  润新知