方法器 --- 策略模式(Strategy Pattern)

1.这是我自己总结出来的,结合比较器。

如果函数有多个策略实现,可以用策略接口进行封装 ,如果函数有n个策略实现,那我们就创建n个继承策略接口的类,然后再进行重写。

例如:吃饭函数,可以用筷子吃,也可以用勺子吃,如果前期选择用筷子吃策略,后期想用勺子策略吃,就只能将筷子策略注释掉进行重写了,又或者前期引入if else 语句,但会导致不好维护。

java 复制代码
// 1. 定义策略接口
public interface Fun {
    public void function();
}

// 2. 具体策略实现
public class FunA implements Fun {
    public void function() {
        System.out.println("FunA具体实现");
    }
}

public class FunB implements Fun {
    public void function() {
        System.out.println("FunB具体实现");
    }
}

// 3. 上下文类使用策略
public class Main {
    public static void test(Fun f) {  // 接收接口类型,多态的体现
        f.function();
    }
    
    public static void main(String[] args) {
        test(new FunB());  // 使用策略B
        test(new FunA());  // 使用策略A
    }
}

2.更完整的例子:排序策略

java 复制代码
// 策略接口
interface SortStrategy {
    void sort(int[] array);
}

// 具体策略
class BubbleSort implements SortStrategy {
    public void sort(int[] array) {
        System.out.println("使用冒泡排序");
        // 实现冒泡排序算法
    }
}

class QuickSort implements SortStrategy {
    public void sort(int[] array) {
        System.out.println("使用快速排序");
        // 实现快速排序算法
    }
}

class MergeSort implements SortStrategy {
    public void sort(int[] array) {
        System.out.println("使用归并排序");
        // 实现归并排序算法
    }
}

// 上下文类
class Sorter {
    private SortStrategy strategy;
    
    public void setStrategy(SortStrategy strategy) {
        this.strategy = strategy;
    }
    
    public void executeSort(int[] array) {
        strategy.sort(array);
    }
}

// 使用
public class Main {
    public static void main(String[] args) {
        Sorter sorter = new Sorter();
        int[] data = {5, 2, 8, 1, 9};
        
        // 动态切换策略
        sorter.setStrategy(new BubbleSort());
        sorter.executeSort(data);
        
        sorter.setStrategy(new QuickSort());
        sorter.executeSort(data);
    }
}
相关推荐
一雨方知深秋12 小时前
面向对象编程
java·封装·this·构造器·static关键字·成员变量·javabean实体类
资生算法程序员_畅想家_剑魔12 小时前
Java常见技术分享-11-责任链模式
java·spring boot·责任链模式
计算机程序设计小李同学13 小时前
动漫之家系统设计与实现
java·spring boot·后端·web安全
程序员阿鹏13 小时前
责任链模式
java·spring·servlet·tomcat·maven·责任链模式
@淡 定13 小时前
Java内存模型(JMM)详解
java·开发语言
czhc114007566314 小时前
C# 1221
java·servlet·c#
黄俊懿14 小时前
【深入理解SpringCloud微服务】Seata(AT模式)源码解析——全局事务的回滚
java·后端·spring·spring cloud·微服务·架构·架构师
派大鑫wink14 小时前
【Day12】String 类详解:不可变性、常用方法与字符串拼接优化
java·开发语言
JIngJaneIL14 小时前
基于springboot + vue健康管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端
秋饼14 小时前
【三大锁王争霸赛:Java锁、数据库锁、分布式锁谁是卷王?】
java·数据库·分布式