策略模式
抽象策略类
interface SortService{
int[] sort(int arr[]);
}
具体策略类
class InsertionSortServiceImpl implements SortService{
@Override
public int[] sort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int j = i-1;
int tmp = arr[i];
for (; j >= 0; --j) {
if (arr[j] > tmp){
arr[j+1] = arr[j];
}
else {
break;
}
}
arr[j+1] = tmp;
}
return arr;
}
}
冒泡排序
class BubbleSortServiceImpl implements SortService{
@Override
public int[] sort(int[] arr) {
for (int i = arr.length-1; i >= 0 ; --i) {
for (int j = 0; j < i; j++) {
if (arr[j] > arr[j+1]){
int tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
return arr;
}
}
常规调用
class ArrayHandle implements SortService{
private Sort sortObj;
public void setSortObj(Sort sortObj) {
this.sortObj = sortObj;
}
@Override
public int[] sort(int[] arr) {
return sortObj.sort(arr);
}
}
Spring整合策略模式
/**
* @author yecxf
* @created time 2020/11/3 23:47
* SortContext容器
*/
@Service
public class SortContextService {
private Map<String, SortService> map = new HashMap<>();
// 将所有实现 SortService 接口的子类注入进来
@Autowired
public SortContextService(Map<String,SortService> hashMap){
this.map = hashMap;
}
public SortService getSortService(String key){
return map.get(key);
}
}
调用
@Autowired
private SortContextService sortContextService;
@Test
public void testSortStrategy(){
SortService bubbleSortServiceImpl = sortContextService.getSortService("bubbleSortServiceImpl");
int a[] = {123,1234,41,4};
int[] sortResult = bubbleSortServiceImpl.sort(a);
for (int i : sortResult) {
System.out.println(i);
}
}
策略设计模式是将算法的定义与使用分开
工厂设计模式是将对象的创建和使用分开