Java - 考虑用静态工厂方法代替构造器
2015-01-15 08:45:26

Effective Item - 考虑用静态工厂方法代替构造器我们有两种常见的方法获得一个类的实例:

public static BigInteger probablePrime(int bitLength, Random rnd) {

if (bitLength < 2)

throw new ArithmeticException("bitLength < 2");

// The cutoff of 95 was chosen empirically for best performance

return (bitLength < SMALL_PRIME_THRESHOLD ?

smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :

largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));

}

private static BigInteger largePrime(int bitLength, int certainty, Random rnd) {

BigInteger p;

p = new BigInteger(bitLength, rnd).setBit(bitLength-1);

p.mag[p.mag.length-1] &= 0xfffffffe;

// Use a sieve length likely to contain the next prime number

int searchLen = (bitLength / 20) * 64;

BitSieve searchSieve = new BitSieve(p, searchLen);

BigInteger candidate = searchSieve.retrieve(p, certainty, rnd);

while ((candidate == null) || (candidate.bitLength() != bitLength)) {

p = p.add(BigInteger.valueOf(2*searchLen));

if (p.bitLength() != bitLength)

p = new BigInteger(bitLength, rnd).setBit(bitLength-1);

p.mag[p.mag.length-1] &= 0xfffffffe;

searchSieve = new BitSieve(p, searchLen);

candidate = searchSieve.retrieve(p, certainty, rnd);

}

return candidate;

}

public static final Boolean TRUE = new Boolean(true);

public static final Boolean FALSE = new Boolean(false);

public static Boolean valueOf(boolean b) {

return (b ? TRUE : FALSE);

}

/**

* Creates an empty enum set with the specified element type.

*

* @param elementType the class object of the element type for this enum

*     set

* @throws NullPointerException if <tt>elementType</tt> is null

*/

public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) {

Enum[] universe = getUniverse(elementType);

if (universe == null)

throw new ClassCastException(elementType + " not an enum");

if (universe.length <= 64)

return new RegularEnumSet<>(elementType, universe);

else

return new JumboEnumSet<>(elementType, universe);

}

public static <K, V> HashMap<K, V> newInstance() {

return new HashMap<K, V>();

}

Map<String,List<Integer>> n = newInstance();

Map<String,List<Integer>> m = new HashMap<String,List<Integer>>();

Java7开始这一点变得没有意义，事实上Josh Bloch也在书上提到了这点——Java以后会在构造器和方法调用中执行这种类型推导。