java設計模式連載(1)—Factory 方法模式

來源:互聯網
上載者:User

1.      java設計模式連載(1)---Factory 方法模式

 

         意圖:

               定義一個用於建立對象的介面,讓子類決定執行個體化哪一個類。Factory Method 使一個類的執行個體化延遲到其子類。

      

        適用性:

  • 當一個類不知道它所必須建立的對象的類的時候。
  • 當一個類希望由它的子類來指定它所建立的對象的時候。
  • 當類將建立對象的職責委託給多個協助子類中的某一個,並且你希望將哪一個協助子類是代理者這一資訊局部化的時候。

           執行個體:

                1. 定義一個生產衣服的工廠介面

package Factory_Method_Pattern;public interface ClothesFactory  {  public  Clothes  productClothes();      }

   

               2.  實現這個衣服工廠介面,具體生產什麼類型的衣服。

package Factory_Method_Pattern;public class AdultClothesFactory implements ClothesFactory {@Overridepublic  Clothes  productClothes() {  return  new  AdultClothes();}}

 

package Factory_Method_Pattern;public class ChildClothesFactory implements ClothesFactory {@Overridepublic  Clothes  productClothes() {  return new  ChildClothes();}}

3.  定義衣服介面(衣服是用來穿的)

      

package Factory_Method_Pattern;public interface Clothes{ public  void  dressClothes();}

4.   實現衣服介面,什麼樣的衣服,什麼人穿

package Factory_Method_Pattern;public class  AdultClothes  implements  Clothes{@Overridepublic void dressClothes() {         System.out.println("大朋友衣服廠生產的衣服,大朋友穿");         }}

 

package Factory_Method_Pattern;public class  ChildClothes  implements Clothes{@Overridepublic void dressClothes() {         System.out.println("小朋友衣服廠生產的衣服,小朋友穿");         }}

 

5. 測試這個模式

 

package Factory_Method_Pattern;public class Test{    public static void main(String[] args){           ClothesFactory  clothesFactory =  new    ChildClothesFactory();               clothesFactory.productClothes().dressClothes();                ClothesFactory    adultClothesFactory  =  new AdultClothesFactory();                adultClothesFactory.productClothes().dressClothes();        }}

6. 多謝瀏覽,歡迎斧正。

  

     

 

 

 

聯繫我們

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