策略模式及Spring整合策略模式

策略模式

抽象策略类

    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);
     }
 }

策略设计模式是将算法的定义与使用分开

工厂设计模式是将对象的创建和使用分开

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值