考慮用靜態Factory 方法替代構造器的情況

來源:互聯網
上載者:User

標籤:

考慮用靜態Factory 方法替代構造器原來建立一個自訂類的執行個體最常用的方法是採用構造器,但一個類可以有多個構造器,而所有的構造器名字都相同,我們只能通過參數來區分不同構造器的作用。除了採用構造器外,還可以採用靜態Factory 方法,該方法返回類的執行個體便可,自訂的方法可以自己命名,這樣一來就很容易區分每個方法的作用了。例子:

publicclass CreateObject {

   intage;

   String name;

   public CreateObject(String name){

      this.name = name;

   }

   public CreateObject(String name,int age){

      this.name = name;

      this.age = age;

   }

   //....

   publicstatic CreateObject getInstanceWithName(String name){

      returnnew CreateObject(name);

   }

   publicstatic CreateObject getInstanceWithNameAndAge(String name,int age){

      returnnew CreateObject(name, age);

   }

   publicstaticvoid main(String[]args){

      CreateObject createObject = new CreateObject("nnn");

      CreateObject createObject2 = new CreateObject("nnn", 11);

      CreateObject createObject3 = CreateObject.getInstanceWithName("mmm");

      CreateObject createObject4 = CreateObject.getInstanceWithNameAndAge("mmm", 22);

   }

}

靜態Factory 方法好處:1、靜態Factory 方法有名稱2、可以用於建立單例模式,而構造器每次都會建立一個新執行個體3、可以返回該類的任何子類,從而可以實現子類的靈活執行個體化





著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

考慮用靜態Factory 方法替代構造器的情況

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.