zoukankan      html  css  js  c++  java
  • 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("离间成功");
            }
    }

    策略模式适用场景

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

         

  • 相关阅读:
    中国的南方人和北方人有什么区别?总算说透了!
    怎样通过穴位按摩来减轻脚踝扭伤的疼痛
    关于脚踝不得不说的各种事
    电影发烧友必备知识-720P、1080P、4K的区别
    有什么相见恨晚的小知识?
    男生有钱到底有多重要?
    es6学习笔记5--promise
    es6学习笔记4--数组
    js设计模式总结1
    es6学习笔记3--解构和对象
  • 原文地址:https://www.cnblogs.com/liaoweipeng/p/5791058.html
Copyright © 2011-2022 走看看