(1)写一个共有的接口和类型获取接口,需要干的事情
package com.winter.strategy;
/**
* Created with IntelliJ IDEA.
* Description:策略分配中心基础接口
*
* @PROJECT_NAME: StudySpringBootProject
* @author: LiYong
* @date: 2019-01-22 10:37
*/
public interface ICacludeCenter {
public ICacludeService getCacludeService(int type);
}
package com.winter.strategy;
/**
* Created with IntelliJ IDEA.
* Description:基础接口
*
* @PROJECT_NAME: StudySpringBootProject
* @author: LiYong
* @date: 2019-01-22 10:33
*/
public interface ICacludeService {
public int calculate(int a,int b);
public int getType();
}
(2)实现这个接口的抽象类,抽象类可以包含共有的业务逻辑
package com.winter.strategy.impl;
import com.winter.strategy.ICacludeService;
/**
* Created with IntelliJ IDEA.
* Description:抽象类,可以添加每一种实现公共的业务方法或者其它
*
* @PROJECT_NAME: StudySpringBootProject
* @author: LiYong
* @date: 2019-01-22 10:39
*/
public class AbstractICacludeService implements ICacludeService {
@Override
public int calculate(int a, int b) {
return 0;
}
@Override
public int getType() {
return 0;
}
}
(3)写一个具体的实现类,继承抽象类
package com.winter.strategy.impl.strategyimpl;
import com.winter.strategy.impl.AbstractICacludeService;
import org.springframework.stereotype.Service;
/**
* Created with IntelliJ IDEA.
* Description:针对共同接口进行的不行实现之一
*
* @PROJECT_NAME: StudySpringBootProject
* @author: LiYong
* @date: 2019-01-22 10:50
*/
@Service
public class AddCacludeServiceImpl extends AbstractICacludeService {
private static int type=1;
@Override
public int calculate(int a, int b) {
return a+b;
}
@Override
public int getType() {
return type;
}
}
(4)写一个策略调用中心接口和实现类,主要负责根据不同的类型调用不同的实现类
package com.winter.strategy.impl;
import com.winter.strategy.ICacludeCenter;
import com.winter.strategy.ICacludeService;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* Description:策略调度中心,可以根据tup判断调用哪一个实现类
*
* @PROJECT_NAME: StudySpringBootProject
* @author: LiYong
* @date: 2019-01-22 10:56
*/
@Service
public class CacludeCenter implements ICacludeCenter , InitializingBean {
@Autowired
List<ICacludeService> iCacludeServiceList;
private Map<Integer ,ICacludeService> map=new HashedMap();
@Override
public ICacludeService getCacludeService(int type) {
return map.get(type);
}
//这里重写spring的初始化
@Override
public void afterPropertiesSet() throws Exception {
if(iCacludeServiceList!=null && iCacludeServiceList.size()>0){
for (ICacludeService service:iCacludeServiceList) {
map.put(service.getType(),service);
}
}
}
}