泛型和设计模式提供了强大的工具来提高 java 函数的可重用性。泛型允许函数在不同类型上运行,而设计模式提供可重用的代码模式:策略模式:封装算法行为,允许在不更改客户端代码的情况下更改算法。模板方法模式:定义算法框架,让子类提供特定实现。
如何使用泛型和设计模式提高 Java 函数的可重用性
在 Java 中,函数的可重用性对于保持代码简洁、可读和可维护性非常重要。泛型和设计模式是实现可重用性的两种强大工具。
泛型
泛型允许您创建可在不同类型上运行的代码,而无需编写单独的函数或类。例如,以下函数使用泛型类型 T 计算两个值的最小值:
public static> T min(T a, T b) { return a.compareTo(b) < 0 ? a : b; }
这个函数可以与任何实现了 Comparable 接口的类型一起使用,例如 Integer、String 和自定义类型。
设计模式
设计模式提供了可重用代码模式的集合,可解决常见编程问题。以下是一些可用于提高函数可重用性的设计模式:
实战案例
让我们使用泛型和策略模式创建一个可重用函数来对列表排序。首先,我们定义一个 Sortable 接口,用于表示可排序的类型:
public interface Sortable{ int compareTo(T other); }
然后,我们创建两个策略,升序和降序:
publicclass AscendingComparator
> implements Comparator { @Override public int compare(T a, T b) { return a.compareTo(b); } } public class DescendingComparator > implements Comparator { @Override public int compare(T a, T b) { return -a.compareTo(b); } }
最后,我们使用策略模板方法模式创建排序函数:
public static> void sort(List list, Comparator comparator) { list.sort(comparator); }
我们可以像这样使用 sort 函数:
Listnumbers = List.of(5, 2, 8, 1); sort(numbers, new AscendingComparator<>()); System.out.println(numbers); // 输出: [1, 2, 5, 8] List strings = List.of("apple", "banana", "cat"); sort(strings, new DescendingComparator<>()); System.out.println(strings); // 输出: [zip, yellow, zebra]