方法器 --- 策略模式(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);
    }
}
相关推荐
xiaoshuaishuai84 分钟前
C# AvaloniaUI 资源找不到报错
java·服务器·前端·windows·c#
我是唐青枫29 分钟前
Java JdbcTemplate 实战指南:用 Spring 轻量完成数据库增删改查
java·数据库·spring
Lumbrologist1 小时前
【C++】零基础入门 · 第 13 节:类与对象基础
java·c++·算法
码不停蹄的玄黓1 小时前
Java 生产者-消费者模型详解
java·开发语言·python
笨蛋不要掉眼泪1 小时前
Java并发编程:Executors框架类深度解析
java·开发语言·并发
南极企鹅1 小时前
深入理解 MVCC:数据库并发控制的基石
java·数据库·mysql
凯瑟琳.奥古斯特2 小时前
力扣1235:加权区间调度最优解
java·python·算法·leetcode·职场和发展
想不到ID了2 小时前
第八篇: 登录注册功能实现
java·javascript
码语智行2 小时前
shp文件生成
java
plainGeekDev2 小时前
AlertDialog → DialogFragment
android·java·kotlin