设计模式-策略模式

文章目录

策略模式

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

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

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

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

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));
    }
}
相关推荐
缘来是庄8 小时前
设计模式之访问者模式
java·设计模式·访问者模式
hqxstudying11 小时前
Java创建型模式---单例模式
java·数据结构·设计模式·代码规范
花好月圆春祺夏安12 小时前
基于odoo17的设计模式详解---装饰模式
数据库·python·设计模式
fie888912 小时前
浅谈几种js设计模式
开发语言·javascript·设计模式
哆啦A梦的口袋呀12 小时前
《深入设计模式》模式结构汇总
设计模式
花好月圆春祺夏安12 小时前
基于odoo17的设计模式详解---单例模式
单例模式·设计模式
在未来等你15 小时前
设计模式精讲 Day 22:模板方法模式(Template Method Pattern)
设计模式·模板方法模式·软件架构·java开发·面向对象设计·设计模式实战·java应用开发
花好月圆春祺夏安17 小时前
基于odoo17的设计模式详解---代理模式
设计模式·代理模式
Small black human1 天前
设计模式-应用分层
设计模式
码农秋2 天前
设计模式系列(10):结构型模式 - 桥接模式(Bridge)
设计模式·桥接模式