一、策略工厂模式
1、初始化工厂对象
/**
* 初始化注入对象
*/
@Service
@Slf4j
public class AutoRegisterSortStrategyFactory {
private Map<String,SortStrategy> sortStrategyMap =new HashMap<String,SortStrategy>();
@Resource
List<SortStrategy> sortStrategyList;
/**
* 初始化service到map key为设置的
*/
@PostConstruct
private void initService(){
if(sortStrategyList != null){
sortStrategyList.forEach(sortStrategy -> {
if(sortStrategy.sortCode()!=null)
sortStrategyMap.put(sortStrategy.sortCode(),sortStrategy);
});
}
}
/**
* 获取服务
*/
public SortStrategy getService(String sortCode){
System.out.println(sortStrategyMap.size());
if (StringUtils.isBlank(sortCode)) {
return null;
}
return sortStrategyMap.get(sortCode);
}
}
2、创建接口
public interface SortStrategy {
void sort(int[] elements);
/**
* 原始场景事件编码
* @return
*/
String sortCode();
}
3、创建接口实现类
/**
* 抽像接口可用于处理共用逻辑
*/
public abstract class AbsSortStrategyImpl implements SortStrategy {
@Override
public void sort(int[] elements) {
if(elements == null){
throw new RuntimeException("数组不能为空");
}
test();
}
protected void test(){
}
}
/**
* 冒泡排序接口实现
*/
@Slf4j
@Service
public class BubbleSort extends AbsSortStrategyImpl implements SortStrategy {
@Override
public void sort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1]) {
// 交换 arr[j+1] 和 arr[j]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
@Override
public String sortCode() {
return "bubble";
}
protected void test(){
System.out.println("test");
}
}
@Service
@Slf4j
public class InsertionSort implements SortStrategy {
@Override
public void sort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
/* 将选择的元素与它前面的元素比较,如果选择的元素小,则交换位置 */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
@Override
public String sortCode() {
return "insertion";
}
4、血缘关系
二、策略模式,抽象模式,工厂模式结合,符合开闭原则
1、创建支付接口
2、创建支付抽象实现类,把公共方法抽取出来
3、定义两个实际业务实现类
4、创建工厂注册服务
5、服务的调用