美文网首页
策略模式

策略模式

作者: 码上述Andy | 来源:发表于2019-07-12 23:35 被阅读0次

    1.概述

    策略模式是封装一组算法,在程序运行的过程中根据不同情况执行相应的算法。

    2.UML结构图

    image.png

    3.代码实现:

    Strategy:策略接口

    /**
     * Created by zhouwen on 2019/7/13 17:16
     */
    public interface Strategy {
        void doing();
    }
    

    ConcreteStrategyA:具体策略角色

    /**
     * Created by zhouwen on 2019/7/13 17:16
     */
    public class ConcreteStrategyA implements Strategy {
        @Override
        public void doing() {
            Logger.getLogger("ConcreteStrategyA").info("A doing");
        }
    }
    

    ConcreteStrategyB:具体策略角色

    /**
     * Created by zhouwen on 2019/7/13 17:17
     */
    public class ConcreteStrategyB implements Strategy{
        @Override
        public void doing() {
            Logger.getLogger("ConcreteStrategyB").info("B doing");
        }
    }
    

    StrategyContext:封装角色,屏蔽上层对具体策略直接访问

    /**
     * Created by zhouwen on 2019/7/13 17:17
     */
    public class StrategyContext {
        private Strategy mStrategy;
    
        public StrategyContext(Strategy mStrategy) {
            this.mStrategy = mStrategy;
        }
    
        public void doing(){
            mStrategy.doing();
        }
    }
    

    StrategyClient:场景类

    /**
     * Created by zhouwen on 2019/7/13 17:31
     */
    public class StrategyClient {
        public void test(){
            Strategy strategya = new ConcreteStrategyA();
            Strategy strategyb = new ConcreteStrategyB();
    
            StrategyContext strategyContext = new StrategyContext(strategya);
            strategyContext.doing();
    
            strategyContext = new StrategyContext(strategyb);
            strategyContext.doing();
        }
    }
    

    相关文章

      网友评论

          本文标题:策略模式

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