设计模式-策略模式

文章目录

策略模式

策略模式是一种行为型设计模式,它允许在运行时动态改变对象的行为。在策略模式中,算法被封装在独立的策略类中,使得它们可以互换使用。下面是一个简单的例子:

假设我们有一个计算税收的系统,现在需要计算不同类型的商品的税收,例如书籍、食品和服装。每种商品的税收计算方法都不一样,因此我们可以把每种计算方法都封装在一个具体的策略类中,最终让客户端根据商品类型动态地选择相应的策略进行计算税收。

所谓策略模式就是定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分割开来,并委派给不同的对象对这些算法进行管理。

例如:我们对一个数组进行排序,但是我们不知道数组类型,并且不同数组的排序方式也是不一样的。

java 复制代码
public class Cat {
    int weight, height;
    public Cat(int weight, int height){
        this.weight = weight;
        this.height = height;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "weight=" + weight +
                ", height=" + height +
                '}';
    }

}
java 复制代码
@FunctionalInterface
public interface Comparator<T> {
    int compare(T o1, T o2);
}
java 复制代码
/**
 * 比较器  策略模式的实现
 * 一个接口,类实现这个接口,将策略封装在这个类中,这样就可以由多个策略即多个类
 * 比如线程池的拒绝策略
 */
public class CatComparator implements Comparator<Cat>{
    @Override
    public int compare(Cat o1, Cat o2) {
        if (o1.weight < o2.weight){
            return -1;
        }else if(o1.weight > o2.weight){
            return 1;
        }else {
            return 0;
        }
    }
}
java 复制代码
public class Sorter<T> {

    public void sort(T[] arr, Comparator<T> comparator){
        for (int i = 0; i < arr.length; i++) {
            int minPos = i;
            for (int j = i+1; j < arr.length; j++) {
                minPos = comparator.compare(arr[j], arr[minPos]) == -1 ? j : minPos;
            }
            swap(arr, i, minPos);
        }
    }

    void swap(T[] arr, int i, int j) {
        T cat = arr[i];
        arr[i] = arr[j];
        arr[j] = cat;
    }
}
java 复制代码
/**
 * 策略模式
 * Comparable
 * Comparator
 * 对数组进行排序
 */
public class Strategy01 {
    public static void main(String[] args) {
//        int[] a = {9,2,1,3,5,0};
        Cat[] a = {new Cat(3,3), new Cat(5,5),new Cat(2,2)};
        Sorter<Cat> sorter = new Sorter();
        sorter.sort(a, new CatComparator());
//        //也可以简化实现
//        sorter.sort(a, (o1, o2) -> {
//            if (o1.weight < o2.weight){
//                return -1;
//            }else if(o1.weight > o2.weight){
//                return 1;
//            }else {
//                return 0;
//            }
//        });
        System.out.println(Arrays.toString(a));
    }
}
相关推荐
李广坤15 小时前
状态模式(State Pattern)
设计模式
李广坤16 小时前
观察者模式(Observer Pattern)
设计模式
李广坤17 小时前
中介者模式(Mediator Pattern)
设计模式
李广坤17 小时前
迭代器模式(Iterator Pattern)
设计模式
李广坤18 小时前
解释器模式(Interpreter Pattern)
设计模式
阿无,21 小时前
java23种设计模式之前言
设计模式
Asort21 小时前
JavaScript设计模式(八):组合模式(Composite)——构建灵活可扩展的树形对象结构
前端·javascript·设计模式
数据智能老司机1 天前
数据工程设计模式——数据基础
大数据·设计模式·架构
笨手笨脚の1 天前
设计模式-代理模式
设计模式·代理模式·aop·动态代理·结构型设计模式
Overboom1 天前
[C++] --- 常用设计模式
开发语言·c++·设计模式