java设计模式-策略模式

2017-12-02  本文已影响0人  MrKing5946

在我们需要实现一个功能的时候,可以有多种算法来实现的时候,我们可以使用if...else或者case来选择对应的算法来实现功能。但是如果又有新的算法添加进来的时候,我们不得不重新修改之前的代码。

那么如何才能够对其进行优雅的编码而不会在有变化的时候去修改我们的原来的代码呢?

定义

策略模式定义了一系列的算法,它们具有共同的一些通性,通过这个通性纽带关联起来,在使用算法的时候可以相互切换。策略模式将算法的本身实现和使用算法隔离开来,这样对于算法的变化从而让调用者无法感知。

结构

strategy.png

策略模式涉及到3个角色:

以一个排序为例

在我们对一组数据排序的时候,可以有多种算法选择:冒泡、选择、插入等等。

抽象策略

public interface ISort {
    void sort(int[] source);
}

具体策略

Context

    public class SortContext {
        private ISort sort;
    
        public void setSort(ISort sort) {
            this.sort = sort;
        }
    
        public void func(int[] source) {
    
            System.out.println("排序前的数据:" + Arrays.toString(source));
            sort.sort(source);
            System.out.println("排序后的数据: " + Arrays.toString(source));
        }
    
        public static void main(String[] args) {
            int[] source = {56,2,345,12,9,7,56};
    
            int[] source1 = source.clone();
            int[] source2 = source.clone();
            int[] source3 = source.clone();
    
            SortContext sortContext = new SortContext();
            sortContext.setSort(new BubbleSort());
            sortContext.func(source1);
            System.out.println("-------------------------------------");
            sortContext.setSort(new ChooseSort());
            sortContext.func(source2);
            System.out.println("-------------------------------------");
            sortContext.setSort(new InsertSort());
            sortContext.func(source3);
        }
    }

结果:

排序前的数据:[56, 2, 345, 12, 9, 7, 56]
排序后的数据: [2, 7, 9, 12, 56, 56, 345]
-------------------------------------
排序前的数据:[56, 2, 345, 12, 9, 7, 56]
排序后的数据: [2, 7, 9, 12, 56, 56, 345]
-------------------------------------
排序前的数据:[56, 2, 345, 12, 9, 7, 56]
排序后的数据: [2, 7, 9, 12, 56, 56, 345]

可以看到,我们使用不同的策略算法来达到了我们目的,在我们的客户端并不清楚它们之间的区别。策略模式的核心就是如何去调度这些算法而不是如何实现这些算法。

策略模式的优点是可以动态的切换算法来改变客户端的行为。但是它的缺点也是比较明显的,客户端需要知道所有的策略实现,如果策略比较多,那么不仅仅是类增加了,客户端管理起来也是一个麻烦事。

上一篇 下一篇

猜你喜欢

热点阅读