Item 1:考慮用靜態Factory 方法代替建構函式

來源:互聯網
上載者:User
 

靜態Factory 方法:實際上只是一個簡單的靜態方法,它返回的類的執行個體。
樣本:public static void Boolean valueOf(boolean b){
                   return toBoolean(s) ? TRUE : FALSE;
    }
    private static boolean toBoolean(String name) { 
    return ((name != null) && name.equalsIgnoreCase("true"));
}
優點:1。靜態Factory 方法具有名字——〉使代碼容易閱讀。
          2.每次調用時,不要求非得建立一個新的對象——〉免去建立對象的代價;可以為重複的調用返回同一個對象,(保證  singleton;保證若且唯若a==b時才有a.equals(b)為true),如String.intern()方法
          3.可以返回一個原傳回型別的字類型的對象——〉在選擇被返回對象的類型時有了更大的靈活性(應用:一個API可以返回一個對象,同時右不使該對象的類成為公有的,這樣可以把具體的實作類別隱藏起來,得到一個簡潔的API)。如Collections Framework有20個實用的集合介面實現,這些實現絕大多數都是通過一個不可執行個體化的類中的靜態Factory 方法而被匯出的,所有返回對象的類都不是公有的。
缺點:1。類如果不含有公有的或保護的建構函式,——〉就不能被子類化。如要想子類化Collections Framework中的任何一個方便的實作類別,是不可能的。
         2.它們與其它靜態方法沒有任何區別。——〉對規範的背離(流行的靜態Factory 方法命名:valueOf,getInstance)

import java.util.*;
//Provider framework sketch
publicabstractclass Foo {
    //Maps String key to corresponding Class object
    privatestatic Map implementations = null;
    //Initializes implementations map the first time it's called
    privatestaticsynchronizedvoid initMapIfNecessary(){
       if (implementations == null){
           implementations = new HashMap();
           //Load implementations class names and keys from
           //Properties file,translate names into Class
           //objects using Class.forName and store mappings.
           //...
      }
    }  
    public static Foo getInstance(String key){
       initMapIfNecessary();
       Class c =(Class)implementations.get(key);
       if (c==null)
           returnnew DefaultFoo();
       try{
           return (Foo)c.newInstance();
       }catch(Exception e){
           returnnew DefaultFoo();
       }
    }
   //entry
    publicstaticvoid main(String[] args) {
           System.out.println(getInstance("NonexistentFoo"));
   }
}
class DefaultFoo extends Foo{}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.