我正在阅读有关工厂设计模式的文章,看到文章中提到的一些示例,如 Integer 和 Boolean 等包装类使用
valueof
方法,该方法返回由工厂创建的对象,该对象等于传递的参数值。
当我检查代码时,我看到下面的代码。我无法理解工厂模式是如何在包装类中实现的。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
就是在
Integer
类中实现的工厂模式。在研究它时,您会注意到它有 3 种不同的实现,根据参数类型 create 和 Integer
。 工厂模式是一个creational模式。
public static Integer valueOf(int i)
public static Integer valueOf(String s)
public static Integer valueOf(String s, int radix)
此外,在
Integer
类的情况下,使用了另一种模式,即静态构造函数,在Effective Java一书中推荐。