初识策略模式

Posted liushengyuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了初识策略模式相关的知识,希望对你有一定的参考价值。

首先谈谈自己对策略模式的理解:

假如业务需求中需要根据不同的任务种类(假设A B等等)作出不同的处理方式,我们是否要采用if else的方式,逐个判断呢?

if(type=="A"){
    //A的处理逻辑
}else if(type=="B"){
    //B的处理逻辑
}
//........

 

以上写法实现功能自然没有问题,但是随着任务种类的增加,我们需要不停的添加或者修改if else判断语句,以及添加或修改相应的处理逻辑,方法也会非常臃肿,亦不符合面向对象的对修改关闭,对拓展开放的原则。

由此,引入策略模式来解决这个问题。

 

以下是我简单模拟的一个策略模式的代码轮廓,实际应用可能要复杂一些,只表明策略模式的思想: 忘记是参考的哪篇博客了.....

 

Handle接口,作为任务处理器的一个简单抽象,定义来返回类型接口 getType 和 处理任务方法 process ,所有的任务处理类都实现Handle接口,根据不同的类型,对应不同的处理逻辑

TypeEnums 枚举则作为任务类型定义所有的任务种类

public interface Handle<T> {

    /**
     * 处理方法
     * @param t
     */
    void process(T t);

    /**
     * 获取类型
     */
    TypeEnums getType();
}
public enum TypeEnums {

    TYPEA("A", "typeA"),
    TYPEB("B", "typeB");

    @Setter
    @Getter
    private String type;

    @Setter
    @Getter
    private String desc;

    TypeEnums(String type, String desc) {
        this.type = type;
        this.desc = desc;
    }
}

ApplicationContextHelper负责获取spring 的容器,通过该容器可以获取到所有实现Handle接口的实现类,也就是所有任务类型的处理器

@Component
public class ApplicationContextHelper implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public <T> Map<String, T> getBeansOfType(Class<T> clazz) {
        return applicationContext.getBeansOfType(clazz);
    }
}
@Component
public class Client<T> implements InitializingBean {

    @Autowired
    private ApplicationContextHelper applicationContextHelper;

/**
* 负责存储所有处理器
**/
private Map<String, Handle> handleMap = new ConcurrentHashMap<>(); @Override public void afterPropertiesSet() throws Exception { Map<String, Handle> handles = applicationContextHelper.getBeansOfType(Handle.class); for (Map.Entry<String, Handle> m : handles.entrySet()) { handleMap.put(m.getValue().getType().getType(), m.getValue()); } System.out.println(); } /**
* 关键的方法,根据类型获得处理器,执行对应的process方法
*/
public void doHandler(String tag, T t) { handleMap.get(tag).process(t); } }

 

public void strategyModel(Client client) {

        StatementDto dto1 = new StatementDto();
        dto1.setType("AHandler");
        client.doHandler(TypeEnums.TYPEA.getType(), dto1);

        StatementDto dto2 = new StatementDto();
        dto2.setType("BHandler");
        client.doHandler(TypeEnums.TYPEB.getType(), dto2);
    }
//运行结果:

AHandler
BHandler

 

策略模式的好处在于如果需求出现变化,如新增任务类型,则添加一个类去实现Handle接口,实现对应的process方法即可,不需要修改原方法

 

以上是关于初识策略模式的主要内容,如果未能解决你的问题,请参考以下文章

初识Kafka

初识Spring源码 -- doResolveDependency | findAutowireCandidates | @Order@Priority调用排序 | @Autowired注入(代码片段

初识Spring源码 -- doResolveDependency | findAutowireCandidates | @Order@Priority调用排序 | @Autowired注入(代码片段

策略模式

策略模式

Java初识方法