君临-行者无界

导航

策略模式

  策略模式作为一种软件设计模式,指对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。比如每个人都要“交个人所得税”,不同的收入要按的税率是不一样的。

  简单截取一个类图

  首先是一个基础版的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类,违反了开闭原则。所以我们需要对其做改进,以增强代码的可维护性。

  自定义一个注解,来标识各个策略类

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;
}

  在策略类分别加上注解

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 

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来管理

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);

    }
}

  以上便是策略模式的使用,下面说下策略模式的优缺点

  优点:

  1、 策略模式提供了管理相关的算法族的办法。策略类的等级结构定义了一个算法或行为族。恰当使用继承可以把公共的代码转移到父类里面,从而避免重复的代码。
  2、 策略模式提供了可以替换继承关系的办法。继承可以处理多种算法或行为。如果不是用策略模式,那么使用算法或行为的环境类就可能会有一些子类,每一个子类提供一个不同的算法或行为。但是,这样一来算法或行为的使用者就和算法或行为本身混在一起。决定使用哪一种算法或采取哪一种行为的逻辑就和算法或行为的逻辑混合在一起,从而不可能再独立演化。继承使得动态改变算法或行为变得不可能。
  3、 使用策略模式可以避免使用多重条件转移语句。多重转移语句不易维护,它把采取哪一种算法或采取哪一种行为的逻辑与算法或行为的逻辑混合在一起,统统列在一个多重转移语句里面,比使用继承的办法还要原始和落后。

  缺点

  1、客户端必须知道所有的策略类,并自行决定使用哪一个策略类。这就意味着客户端必须理解这些算法的区别,以便适时选择恰当的算法类。换言之,策略模式只适用于客户端知道所有的算法或行为的情况。
  2、 策略模式造成很多的策略类,每个具体策略类都会产生一个新类。有时候可以通过把依赖于环境的状态保存到客户端里面,而将策略类设计成可共享的,这样策略类实例可以被不同客户端使用。换言之,可以使用享元模式来减少对象的数量。

  策略模式应用场景:

  1、 多个类只区别在表现行为不同,可以使用Strategy模式,在运行时动态选择具体要执行的行为。
  2、 需要在不同情况下使用不同的策略(算法),或者策略还可能在未来用其它方式来实现。
  3、 对客户隐藏具体策略(算法)的实现细节,彼此完全独立。

posted on 2019-03-23 21:40  请叫我西毒  阅读(1503)  评论(0编辑  收藏  举报