设计模式-策略模式

文章目录

策略模式

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

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

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

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

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));
    }
}
相关推荐
寅时码1 小时前
React 正在演变为一场不可逆的赛博瘟疫:AI 投毒、编译器迷信与装死的官方
前端·react.js·设计模式
willow3 天前
Axios由浅入深
设计模式·axios
七月丶5 天前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞5 天前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼5 天前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟6 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder6 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室6 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦7 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding