7

设计模式学习(十五):策略模式 - Grey Zeng

 2 years ago
source link: https://www.cnblogs.com/greyzeng/p/16883511.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

设计模式学习(十五):策略模式

作者:Grey

原文地址:

博客园:设计模式学习(十五):策略模式

CSDN:设计模式学习(十五):策略模式

策略模式#

策略模式是一种行为型模式,它定义了一组算法,将每个算法都封装起来,并且使它们之间可以互换。

以实例来说明

假设我们有一个猫类,这个类里面有体重和身高这两个属性,给你一个猫的集合,然后需要你按猫的体重从小到大排序

我们可以把体重从小到大这个看成是一个策略,后续可能衍生其他的策略,比如: 按身高从高到低,体重从小到大,体重一样的身高从高到低……

以「身高从低到高」排序这个策略为例

public class CatSortStrategy implements Comparator<Cat> {
    @Override
    public int compare(Cat o1, Cat o2) {
        return o1.getHeight() - o2.getHeight();
    }
}

假设我们定义猫排序的方法是sort(), 那么这个方法必然需要传入一个排序策略的参数(否则我怎么知道要怎么排序猫?) 所以定义的 sort 方法可以是:

public class Sorter {
    public Cat[] sort(Cat[] items, Comparator<Cat> strategy) {
        int length = items.length;
        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j < length; j++) {
                if (strategy.compare(items[i], items[j]) > 0) {
                    Cat tmp = items[i];
                    items[i] = items[j];
                    items[j] = tmp;
                }
            }
        }
        return items;
    }
}

进一步抽象,如果我想让 Sorter 这个工具类不仅可以对猫进行各种策略的排序(基于比较的排序算法),还可以对狗进行各种策略的排序(基于比较排序算法),可以将 Sorter 定义成泛型

public class Sorter<T> {
    public T[] sort(T[] items, Comparator<T> strategy) {
        int length = items.length;
        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j < length; j++) {
                if (strategy.compare(items[i], items[j]) > 0) {
                    T tmp = items[i];
                    items[i] = items[j];
                    items[j] = tmp;
                }
            }
        }
        return items;
    }
}

调用的时候, 泛型版本的 Sorter 可以对猫和狗都进行基于特定排序策略的排序。

Sorter<Cat> sorter = new Sorter<>();
Cat[] sortedCats = sorter.sort(cats,new CatSortStrategy());
Sorter<Dog> sorter = new Sorter<>();
Dog[] sortedCats = sorter.sort(dogs,new DogSortStrategy());

上述示例的 UML 图如下

image

策略模式的应用

  • Spring 中的 Resource 接口。

UML 和 代码#

UML 图

代码

更多#

设计模式学习专栏

参考资料#


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK