zoukankan      html  css  js  c++  java
  • 设计模式之策略模式

    场景引入:

      小镇的咖啡馆生意越来越好了,但是来自不同地方的顾客也越来越多,有的人喜欢咖啡加糖,有的人喜欢咖啡加牛奶,有的喜欢加炼乳。。。

    咖啡伪代码:

    class 咖啡{
    
        void addSth(String param){
              if(param.equals("糖")){
                  System.out.println("咖啡加糖。。。。");
               }else if(param.equals("牛奶")){
                   System.out.println("咖啡牛奶。。。。");
               }       
        }
    
    }                    

    每次出一种新品种,都要在if..else if..后添加,违反了对开闭原则的,对修改关闭的原则。

    我们可以尝试以下策略模式来解决这个问题。

    1.声明一个策略接口;

    2.往后只要新增加一种口味,都生成一种新的具体策略实现类;

    3.在生成咖啡时,将具体的策略赋值给咖啡,就可以生成不同口味的咖啡啦!

    是不是听起来很棒,那我们来看一下具体的代码实现吧

    代码展示:

    策略接口:

    //策略接口
    interface Strategy{
        void add();
    }

    加糖策略:

    //加糖策略
    class SugarStrategy implements Strategy{
        public void add(){
            System.out.println("add Sugar....");
        }
    }

    加牛奶策略:

    //加牛奶策略
    class MilkStrategy implements Strategy{
        public void add(){
            System.out.println("add Milk....");
        }
    }

    具体的咖啡接收类:

    class Coffee{
        //策略
        private Strategy strategy;
        
        public void setStrategy(Strategy strategy){
            this.strategy=strategy;
        }
        
         //烧水
        private void boilWater(){
            System.out.println("boil water...");
        }
        //煮咖啡
        void cook(){
          System.out.println("cook coffee....");  
        }
        //倒咖啡到杯子中
        private void dumpWater(){
            System.out.println("dump water into cup...");
        }
        
        public void doSth(){
            boilWater();
            cook();
            dumpWater();
            if(strategy != null){
                strategy.add();
            }
        }
    }

    测试类:

    //测试类
    public class Test{    
        public static void main(String[] args){  
            Strategy strategy = new MilkStrategy();
            Coffee coffee = new Coffee();
            coffee.setStrategy(strategy);
            coffee.doSth();
            System.out.println("============================");
            strategy = new SugarStrategy();
            coffee.setStrategy(strategy);
            coffee.doSth();
        }
    }
    View Code

    测试结果:

  • 相关阅读:
    复制某文件夹及其子文件夹中的一定大小的文件
    一个简单的查询脚本
    写一个交互的脚本
    nginx+php5.6.12+discuz
    curl 错误
    python 交互界面tab补全
    uwsgi.xml
    supervisorctl
    认识nginx配置文件
    nginx+uwsgi+django 配置3
  • 原文地址:https://www.cnblogs.com/zjting/p/11393927.html
Copyright © 2011-2022 走看看