1. 通常我們創(chuàng)建對象的方法有兩種:
a. 使用類公有的構(gòu)造器
b. 使用類的靜態(tài)方法返回一個實例對象
2. 靜態(tài)方法的優(yōu)點:
a. 靜態(tài)工廠方法的名字由自己命名哟玷,而構(gòu)造方法必須與類名相同
//使用構(gòu)造器方法獲取到一個素數(shù)
BigInteger prime = new BigInteger(int, int ,Random);
//使用靜態(tài)工廠方法
BigInteger prime = BigInteger.probablePrime(int, Random);
BigInteger.png
我們可以看到明顯我們使用靜態(tài)方法可以明確知道我們要獲取到的是一個素數(shù)房揭。
b. 構(gòu)造方法每次調(diào)用都會創(chuàng)建一個對象胁附,而靜態(tài)工廠方法則不會每次調(diào)用時都創(chuàng)建要給對象罗岖。**靜態(tài)方法通常會使用預先構(gòu)建好的實例或者將構(gòu)建好的實例緩存起來扬蕊,進行重復利用治宣,從而避免創(chuàng)建不必要的重復對象右犹,比如我們常見的單例模式提澎。****
public class Singleton {
/*
* 利用一個靜態(tài)變量來記錄Singleton類的唯一實例
*/
private static Singleton uniqueInstance;
/*
* 聲明為private,使得只有Singleton類內(nèi)才可以調(diào)用構(gòu)造器
*/
private Singleton(){}
/*
* 通過該方法實例化對象念链,并返回這個實例
*/
public static Singleton getInstance(){
if (uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
c. 靜態(tài)工廠方法可以返回原返回類型的任何子類型對象盼忌,這樣在我們選擇返回對象的類時就有了更大的靈活性
public class Shape {
private Shape(){
}
//根據(jù)類型決定返回的對象
public static Shape newInstance(String type){
if (type.equalsIgnoreCase("triangle")){
return new Triangle();
} else if (type.equalsIgnoreCase("circle")){
return new Circle();
}
return new Shape();
}
public void getName(){
System.out.println("My name is shape");
}
private static class Triangle extends Shape{
public void getName(){
System.out.println("My name is triangle");
}
}
private static class Circle extends Shape{
public void getName(){
System.out.println("My name is circle");
}
}
}
測試:
public static void main(String[] args){
Shape shape = Shape.newInstance("");
Shape triangle = Shape.newInstance("triangle");
Shape circle = Shape.newInstance("circle");
shape.getName();
triangle.getName();
circle.getName();
}
測試結(jié)果:
My name is shape
My name is triangle
My name is circle
d. 靜態(tài)方法在創(chuàng)建參數(shù)化類型實例時,可以使代碼更加簡潔
//構(gòu)造方法
Map<String,List<String>> map = new HashMap<String,List<String>>();
//靜態(tài)方法
public static <K,V> HashMap<K,V> newInstance(){
return new HashMap<K,V>();
}
Map<String,List<String>> map = HashMap.newInstance();
但實際上钓账,現(xiàn)在Java最新的版本已經(jīng)構(gòu)造函數(shù)已經(jīng)不需要補充參數(shù)了碴犬。
HashMap<String,List<String>> map = new HashMap<>();
靜態(tài)方法的缺點:
a. 類如果不含有公有的類或者受保護的構(gòu)造器,就不能被子類化
b. 它們與其他的靜態(tài)方法實際上沒什么區(qū)別梆暮,因此我們約定了一些靜態(tài)工廠方法的常用名稱
static_name