优先考虑泛型的方法

来源:互联网 发布:淘宝店铺袜子标志 编辑:程序博客网 时间:2024/06/08 23:59

泛型单例工厂模式

package com.innitech;interface UnaryFunctions<T> {T apply(T org);}public class Unary {public static void main(String[] args) {String[] strings = { "jute", "hemp", "nylon" };UnaryFunctions<String> sameString = identityFunction();for (String string : strings) {System.out.println(sameString.apply(string));}Number[] numbers = { 1, 2.0, 3L };UnaryFunctions<Number> sameNumber = identityFunction();for (Number number : numbers) {System.out.println(sameNumber.apply(number));}}private static UnaryFunctions<Object> IDENTITY_FUNCTION = new UnaryFunctions<Object>() {public Object apply(Object org) {return org;}};@SuppressWarnings("unchecked")public static <T> UnaryFunctions<T> identityFunction() {return (UnaryFunctions<T>) IDENTITY_FUNCTION;}}
有时,会需要创建不可变但又适合于许多不同的对象。由于泛型是通过擦除实现的,可以给所有必要的类型参数使用单个对象,但是需要编写一个静态工厂方法,重复地给每个必要的类型参数分发对象。这种模式最常用于函数对象,如Collections.reverseOrder,但也适合用于像Collections.emptySet这样的集合。


递归类型限制:

public static <T extends Comparable<T>> T max(List<T> list) {Iterator<T> i = list.iterator();T result = i.next();while(i.hasNext()) {T t = i.next();if (t.compareTo(result) > 0)result = t;}return result;}

泛型方法就像泛型一样,使用起来比要求客户端转换输入参数并返回值的方法来得更加安全,也更加容易。就像类型一样,你应该确保新方法可以不用转换就能使用,这通常意味着要它们泛型化。并且就像类型一样,还应该将现有的方法泛型化,使新用户使用起来更加轻松,且不会破坏现有的客户端。

摘抄自:Effective Java

原创粉丝点击