策略模式做为一种软件设计模式,指对象有某个行为,可是在不一样的场景中,该行为有不一样的实现算法。好比每一个人都要“交我的所得税”,不一样的收入要按的税率是不同的。java
简单截取一个类图web
首先是一个基础版的demo算法
package com.example.test.stratergy; public interface TaxRate { Double TaxPayable(Double income); }
package com.example.test.stratergy.strategyClass; import com.example.test.stratergy.RateAnnotation; import com.example.test.stratergy.TaxRate; public class Under3000 implements TaxRate { @Override public Double TaxPayable(Double income) { return income *0.03; } }
package com.example.test.stratergy.strategyClass; import com.example.test.stratergy.RateAnnotation; import com.example.test.stratergy.TaxRate; public class Between3000And12000 implements TaxRate { @Override public Double TaxPayable(Double income) { return (income-3000)*0.1 + 3000*0.03; } }
package com.example.test.stratergy.strategyClass; import com.example.test.stratergy.RateAnnotation; import com.example.test.stratergy.TaxRate; public class Exceed12000 implements TaxRate { @Override public Double TaxPayable(Double income) { return (income-12000)*0.2 + 9000*0.1 + 3000*0.03; } }
package com.example.test.stratergy; import com.example.test.stratergy.strategyClass.Between3000And12000; import com.example.test.stratergy.strategyClass.Exceed12000; import com.example.test.stratergy.strategyClass.Under3000; public class RatePayer { private TaxRate taxRate; public double tax(double income) { if (income > 0 && income <= 3000) { taxRate= new Under3000(); } else if (income > 3000 && income <= 12000) { taxRate= new Between3000And12000(); } else { taxRate= new Exceed12000(); } return taxRate.TaxPayable(income); } }
这样咱们便实现了标准版的策略模式,可是这样的程序在咱们的策略类少的状况下或许还能够,策略类多的时候就避免不了大量的ifelse,这样的代码很不优雅,而且每次须要去修改Context类,违反了开闭原则。因此咱们须要对其作改进,以加强代码的可维护性。spring
自定义一个注解,来标识各个策略类设计模式
package com.example.test.stratergy; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented public @interface RateAnnotation { public double min()default 0d; public double max() default 99999999d; }
在策略类分别加上注解app
package com.example.test.stratergy.strategyClass; import com.example.test.stratergy.RateAnnotation; import com.example.test.stratergy.TaxRate; @RateAnnotation(min = 0,max = 3000) public class Under3000 implements TaxRate { @Override public Double TaxPayable(Double income) { return income *0.03; } }
package com.example.test.stratergy.strategyClass; import com.example.test.stratergy.RateAnnotation; import com.example.test.stratergy.TaxRate; @RateAnnotation(min =3000,max = 12000) public class Between3000And12000 implements TaxRate { @Override public Double TaxPayable(Double income) { return (income-3000)*0.1 + 3000*0.03; } }
package com.example.test.stratergy.strategyClass; import com.example.test.stratergy.RateAnnotation; import com.example.test.stratergy.TaxRate; @RateAnnotation(min=12000) public class Exceed12000 implements TaxRate { @Override public Double TaxPayable(Double income) { return (income-12000)*0.2 + 9000*0.1 + 3000*0.03; } }
定义一个工厂类,负责加载策略类,解析其上的注解,根据条件返回对应的策略框架
package com.example.test.stratergy; import java.io.File; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.List; public class StrategyFactory { private static final String strategyPackage = "com.example.test.stratergy.Impl"; private List<Class<? extends TaxRate>> classList = new ArrayList<>(); private ClassLoader loader = this.getClass().getClassLoader(); private StrategyFactory(){ init(); } public TaxRate cteateTaxRateStrategy(double income){ System.out.println(classList.size()); for (Class<? extends TaxRate> clazz: classList) { RateAnnotation rateAnnotation = handleAnnotation(clazz); if(income >rateAnnotation.min() && income <=rateAnnotation.max()) { try { return clazz.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } return null; } private RateAnnotation handleAnnotation(Class<? extends TaxRate> clazz){ Annotation[] annotations = clazz.getDeclaredAnnotations(); if(annotations==null || annotations.length ==0){ return null; } for (Annotation annotation:annotations) { if(annotation instanceof RateAnnotation){ return (RateAnnotation)annotation; } } return null; } public void init(){ File[] TaxRateClasses = getFiles(); Class<TaxRate> TaxRateClass = null; try { TaxRateClass = ( Class<TaxRate>)loader.loadClass(TaxRate.class.getName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } for (File file: TaxRateClasses) { try { Class<?> clazz = loader.loadClass(strategyPackage + "."+file.getName().replace(".class","")); if(TaxRate.class.isAssignableFrom(clazz) && clazz !=TaxRateClass){ classList.add((Class<? extends TaxRate>)clazz); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } } private File[] getFiles(){ try { File file = new File(loader.getResource(strategyPackage.replace(".","/")).toURI()); return file.listFiles((File filepath) ->{ if(filepath.getName().endsWith(".class")){ return true; }else{ return false; } }); } catch (Exception e) { e.printStackTrace(); } return null; } public static StrategyFactory getInstance(){ return InnerFactory.strategyFactory; } private static class InnerFactory{ private static StrategyFactory strategyFactory = new StrategyFactory(); } }
修改RatePayer ide
package com.example.test.stratergy; public class RatePayer { private TaxRate taxRate; public double tax(double income){ taxRate = StrategyFactory.getInstance().cteateTaxRateStrategy(income); return taxRate.TaxPayable(income); } }
这样咱们就去除了ifelse的结构,而且程序的扩展性很强,若是有新的策略,只须要在工厂类加载的包中添加对应的类便可。在目前的java项目开发中,相信你们都是基于spring框架的,那么咱们就能够利用spring的ioc技术来实现优雅的策略模式。测试
首先咱们的策略类加上@Service注解,由spring来管理this
package com.example.test.service.Impl; import com.example.test.stratergy.RateAnnotation; import com.example.test.service.TaxRate; import org.springframework.stereotype.Service; @Service @RateAnnotation(min = 0,max = 3000) public class Under3000 implements TaxRate { @Override public Double TaxPayable(Double income) { return income *0.03; } }
package com.example.test.service.Impl; import com.example.test.stratergy.RateAnnotation; import com.example.test.service.TaxRate; import org.springframework.stereotype.Service; @Service @RateAnnotation(min =3000,max = 12000) public class Between3000And12000 implements TaxRate { @Override public Double TaxPayable(Double income) { return (income-3000)*0.1 + 3000*0.03; } }
package com.example.test.service.Impl; import com.example.test.stratergy.RateAnnotation; import com.example.test.service.TaxRate; import org.springframework.stereotype.Service; @Service @RateAnnotation(min=12000) public class Exceed12000 implements TaxRate { @Override public Double TaxPayable(Double income) { return (income-12000)*0.2 + 9000*0.1 + 3000*0.03; } }
而后再须要使用的地方,经过@autowire注入全部的策略类
package com.example.test.controller; import com.example.test.service.TaxRate; import com.example.test.stratergy.RateAnnotation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @author * @description测试Controller */ @RestController public class TestController { @Autowired private List<TaxRate> list; @GetMapping("/test") public void tax(Double income){ System.out.println(list.size()); for (TaxRate taxRate:list) { RateAnnotation rateAnnotation = taxRate.getClass().getDeclaredAnnotation(RateAnnotation.class); if(income> rateAnnotation.min() && income<= rateAnnotation.max()) { System.out.println("应缴税款" + taxRate.TaxPayable(income)+ "元"); return; } } System.out.println(11111111); } }
以上即是策略模式的使用,下面说下策略模式的优缺点
优势:
一、 策略模式提供了管理相关的算法族的办法。策略类的等级结构定义了一个算法或行为族。恰当使用继承能够把公共的代码转移到父类里面,从而避免重复的代码。
二、 策略模式提供了能够替换继承关系的办法。继承能够处理多种算法或行为。若是不是用策略模式,那么使用算法或行为的环境类就可能会有一些子类,每个子类提供一个不一样的算法或行为。可是,这样一来算法或行为的使用者就和算法或行为自己混在一块儿。决定使用哪种算法或采起哪种行为的逻辑就和算法或行为的逻辑混合在一块儿,从而不可能再独立演化。继承使得动态改变算法或行为变得不可能。
三、 使用策略模式能够避免使用多重条件转移语句。多重转移语句不易维护,它把采起哪种算法或采起哪种行为的逻辑与算法或行为的逻辑混合在一块儿,通通列在一个多重转移语句里面,比使用继承的办法还要原始和落后。
缺点
一、客户端必须知道全部的策略类,并自行决定使用哪个策略类。这就意味着客户端必须理解这些算法的区别,以便适时选择恰当的算法类。换言之,策略模式只适用于客户端知道全部的算法或行为的状况。
二、 策略模式形成不少的策略类,每一个具体策略类都会产生一个新类。有时候能够经过把依赖于环境的状态保存到客户端里面,而将策略类设计成可共享的,这样策略类实例能够被不一样客户端使用。换言之,可使用享元模式来减小对象的数量。
策略模式应用场景:
一、 多个类只区别在表现行为不一样,可使用Strategy模式,在运行时动态选择具体要执行的行为。 二、 须要在不一样状况下使用不一样的策略(算法),或者策略还可能在将来用其它方式来实现。 三、 对客户隐藏具体策略(算法)的实现细节,彼此彻底独立。