策略模式是很好用的设计模式,spring实现策略模式更加简化了代码流程:
xml和纯注解都可以实现,但是纯注解更加方便,没有配置,更加方便:先看注解的方式:
公共接口被实现
package org.gyy.strategy.iface;
public interface IContextStrategy {
void say(String name);
}
实现类:
package org.gyy.strategy.impl;
import org.gyy.strategy.iface.IContextStrategy;
import org.springframework.stereotype.Component;
@Component("aLIContextStrategy")
public class ALIContextStrategy implements IContextStrategy {
@Override
public void say(String name) {
System.out.println("阿里巴巴集团欢迎你:"+name);
}
}
package org.gyy.strategy.impl;
import org.gyy.strategy.iface.IContextStrategy;
import org.springframework.stereotype.Component;
@Component("bDUContextStrategy")
public class BDUContextStrategy implements IContextStrategy{
@Override
public void say(String name) {
// TODO Auto-generated method stub
System.out.println("百度集团欢迎你:"+name);
}
}
package org.gyy.strategy.impl;
import org.gyy.strategy.iface.IContextStrategy;
import org.springframework.stereotype.Component;
@Component("tENContextStrategy")
public class TENContextStrategy implements IContextStrategy {
@Override
public void say(String name) {
// TODO Auto-generated method stub
System.out.println("腾讯集团欢迎你:"+name);
}
}
工厂:spring在对map注入时,会将类名作为key
package org.gyy.strategy;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.gyy.strategy.iface.IContextStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Data
@Component
public class ContextStrategyFactory {
/**
*
* 功能描述: 线程安全的map
*
* @param:
* @return:
* @auther: PC_gongyiyang
* @date: 2018/9/28 17:08
*/
@Autowired
private Map<String, IContextStrategy> contextStrategy = new ConcurrentHashMap<>();
public IContextStrategy doStrategy(String type) {
return this.contextStrategy.get(type);
}
}
测试:
package org.gyy.strategy;
import javax.annotation.Resource;
import org.gyy.baseTest.BaseJunit4Test;
import org.gyy.strategy.iface.IContextStrategy;
import org.junit.Test;
public class StrategyTest extends BaseJunit4Test {
@Resource
private ContextStrategyFactory strategyFactory;
@Test
public void testStrategy(){
IContextStrategy doStrategy = strategyFactory.doStrategy("aLIContextStrategy");
doStrategy.say("张三");
}
}
到这里就是全部的基本实现,如果有复杂的业务需求,可以组合实现具体的方法,
下面是xml的配置,没增加一个实现类就要在map加一个键值对,特别的麻烦:
<bean id="contextStrategyFactory" class="org.gyy.strategy.ContextStrategyFactory">
<property name="contextStrategy">
<map>
<entry key="1" value-ref="aLIContextStrategy"/>
<entry key="2" value-ref="bDUContextStrategy"/>
<entry key="3" value-ref="tENContextStrategy"/>
</map>
</property>
</bean>
<bean id="aLIContextStrategy" class="org.gyy.strategy.impl.ALIContextStrategy"/>
<bean id="bDUContextStrategy" class="org.gyy.strategy.impl.BDUContextStrategy"/>
<bean id="tENContextStrategy" class="org.gyy.strategy.impl.TENContextStrategy"/>