首先給出結(jié)論:創(chuàng)建對(duì)象的時(shí)候考慮用靜態(tài)工廠方法代替構(gòu)造器
靜態(tài)工廠方法:又叫簡單工廠模式,與工廠模式不同,其是通過專門定義一個(gè)類來負(fù)責(zé)創(chuàng)建其他類的實(shí)例邻遏,其實(shí)例通常擁有共同父類消请,其普遍實(shí)現(xiàn)主要依靠Java的反射機(jī)制。
舉個(gè)栗子垃你,以BigInteger中的源碼為例:
構(gòu)造器:
//返回的可能為素?cái)?shù)
public BigInteger(int bitLength, int certainty, Random rnd) {
BigInteger prime;
if (bitLength < 2)
throw new ArithmeticException("bitLength < 2");
prime = (bitLength < SMALL_PRIME_THRESHOLD
? smallPrime(bitLength, certainty, rnd)
: largePrime(bitLength, certainty, rnd));
signum = 1;
mag = prime.mag;
}
靜態(tài)工廠方法,總體功能跟上面的構(gòu)造器差不多,就是certainty參數(shù)這里使用的默認(rèn)值
//返回的可能為素?cái)?shù)
public static BigInteger probablePrime(int bitLength, Random rnd) {
if (bitLength < 2)
throw new ArithmeticException("bitLength < 2");
return (bitLength < SMALL_PRIME_THRESHOLD ?
smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :
largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));
}
那為啥創(chuàng)建對(duì)象靜態(tài)工廠方法好呢
- 靜態(tài)工廠方法有名字BigInteger.probablePrime惜颇,看名字就知道這是要干啥
- 不必在每次調(diào)用它們的時(shí)候都創(chuàng)建一個(gè)新的對(duì)象皆刺,可以進(jìn)行實(shí)例的緩存復(fù)用;因?yàn)殪o態(tài)工廠方法能夠?yàn)橹貜?fù)的調(diào)用返回相同的對(duì)象
- 返回原返回類型任意子類型的對(duì)象凌摄;
比如羡蛾,利用基類,返回該類型的子類
public class FoodFactory {
public static Food getFood(String type) {
Food food = null;
try {
food = (Food) Class.forName("info.zhw." + type).newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return food;
}
- 代碼簡潔
例如: 調(diào)用帶參數(shù)的構(gòu)造器的時(shí)候锨亏,必須2次指明參數(shù)
Map<String,List<String>> m = new HashMap<String,List<String>>;
對(duì)應(yīng)的使用HashMap提供的靜態(tài)工廠方法林说,你只要這么調(diào)用:
Map<String,List<String>> m = HashMap.new Instance();
//是不是代碼短了很多
靜態(tài)工廠方法的缺點(diǎn)
- 類如果不含public或者protected修飾的構(gòu)造器,就不能被子類化
- 與其他的靜態(tài)方法沒有區(qū)別