創(chuàng)建和銷毀對(duì)象
考慮用靜態(tài)工廠方法代替構(gòu)造器
- 一般使用構(gòu)造器
public class Person {
private String name;
public Person(String name){
this.name = name;
}
}
- 使用靜態(tài)方法
public class Person {
private String name;
private Person(String name){
this.name = name;
}
public static Person newInstance(String name){//靜態(tài)工廠方法
return new Person(name);
}
}
這樣寫的優(yōu)勢(shì)
- 靜態(tài)方法有名字
構(gòu)造器與類名相同,如果構(gòu)造器的參數(shù)本身沒(méi)有確切的描述正被返回的對(duì)象,那么具有適當(dāng)名字的靜態(tài)工廠更容易使用,產(chǎn)生的客戶端代碼也更易于閱讀。 - 不必在每次調(diào)用的時(shí)候都創(chuàng)建一個(gè)新對(duì)象
1.這使得不可變類,可以使用預(yù)先構(gòu)建好的實(shí)例,或者將構(gòu)建好的實(shí)例緩存,重復(fù)利用
2.靜態(tài)工廠方法能夠?yàn)橹貜?fù)的調(diào)用返回相同對(duì)象,這樣有助于類總能嚴(yán)格控制在某幾個(gè)時(shí)刻哪些實(shí)例應(yīng)該存在--實(shí)例受控類
實(shí)例受控類可以確保他是一個(gè)singleton或者是不可實(shí)例化的
public class Person {
private static Person mPerson;
private String name;
private Person(String name){
this.name = name;
}
public static Person newInstance(String name) {//靜態(tài)工廠方法
if (mPerson != null) {
mPerson = new Person(name);
}
return mPerson;
}
}
- 它可以返回原返回類型的任何子類型的對(duì)象
public class Person {
public static Person newInstance(String name) {
return Child.newInstance()
}
}
class Child extends Person{
public static Child newInstance{
return new Child();
}
}
通過(guò)代碼很容理解這條原則,那么,這樣寫的好處是什么?
答:隱藏接口的實(shí)現(xiàn)類,使得接口的編寫和調(diào)用更加簡(jiǎn)潔,API可以返回對(duì)象,又不會(huì)使得對(duì)象的類變成公有
代碼舉例
public interface Service {
void method();
}
通過(guò)一個(gè)Service類提供各種接口的實(shí)現(xiàn):
public class Services {
private static final MyService myService = new MyService();
private static final AnotherService anotherService = new AnotherService();
private Services(){}
public static Service getMyService() {//構(gòu)造器
return myService;
}
public static Service getAnotherService(){//構(gòu)造器
return anotherService;
}
private static class MyService implements Service{
@Override
public void method() {
//do some things...
}
}
private static class AnotherService implements Service{
@Override
public void method() {
//do some things...
}
}
}
調(diào)用
Service mySevice = Services.getMyService();
Service anotherService = Services.getAnotherService();
缺點(diǎn)
- 類沒(méi)有公有的或者受保護(hù)的構(gòu)造器,不能被子類化。
- 想要查明如何實(shí)例化的一個(gè)類,非常困難
簡(jiǎn)而言之,靜態(tài)工廠方法和公有構(gòu)造器都各有用處,我們需要理解它們各自的長(zhǎng)處。靜態(tài)工廠通常更加適合,因此切忌第一反應(yīng)就提供公有構(gòu)造器,而不優(yōu)先考慮靜態(tài)工廠。