设计模式---策略模式

  好久没更新了,主要是懒,但还是应该做个记录,打算开个新系列-设计模式,好了回到正题,讲讲我对策略模式的理解:

1、策略模式定义

  策略模式定义算法,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。

2、UML

  

 

3、案例

   上图中的UML用鸭子来举例,有些鸭子会飞,有些鸭子不会飞,策略模式是把不同点提炼出来,使用各自的算法,是面向接口设计。

  抽象策略:

  

  具体策略:

  

  

  封装类:

  

  客户端调用及结果:

  

  

4、实践

   通过以上了解了策略模式,那在实际项目中如何使用呢?我们知道,项目中经常需要写if else语句,当时写的是方便了,当判断条件多了以后,后期的维护就变得越发的困难了,如果你的项目中有使用大量的if else语句的话,就可以通过策略模式来对它进行重构了。

package com.design_pattern.strategy;

public class IfDemo {
    public static void main(String[] args) {
        String phone = "iphone";
        if ("iphone".equals(phone)){
            System.out.println("this is iphone");
        } else if ("hua wei".equals(phone)){
            System.out.println("this is hua wei");
        } else if ("xiao mi".equals(phone)){
            System.out.println("this is xiao mi");
        }
    }
}

  例如上面代码,针对if else部分我们进行重构,先新建phone接口类

package com.design_pattern.strategy;

public interface Phone {
    void doSomething();
}

  再新建子类继承实现方法,这里举个例子,新建两个类IPhone和HuaWei

package com.design_pattern.strategy;

public class IPhone implements Phone {
    @Override
    public void doSomething() {
        System.out.println("this is iphone");
    }
}
package com.design_pattern.strategy;

public class HuaWei implements Phone {
    @Override
    public void doSomething() {
        System.out.println("this is hua wei");
    }
}

  最后建一个策略类

package com.design_pattern.strategy;

public class PhoneStrategy {
    Phone phone;

    public PhoneStrategy(Phone phone) {
        this.phone = phone;
    }

    public void doSomething() {
        phone.doSomething();
    }
}

  如此,我们就对判断部分的代码重构完毕了,运行试试效果吧

package com.design_pattern.strategy;

public class IfDemo {
    public static void main(String[] args) {
//        String phone = "iphone";
//        if ("iphone".equals(phone)){
//            System.out.println("this is iphone");
//        } else if ("hua wei".equals(phone)){
//            System.out.println("this is hua wei");
//        } else if ("xiao mi".equals(phone)){
//            System.out.println("this is xiao mi");
//        }

        PhoneStrategy phoneStrategy = new PhoneStrategy(new IPhone());
        phoneStrategy.doSomething();
    }
}

 

 

 

 

  

 

posted @ 2019-07-28 22:13  那叶扁舟  阅读(89)  评论(0)    收藏  举报