java--物件導向--設計模式--原廠模式

來源:互聯網
上載者:User

標籤:

今天第一次接觸Java的工廠設計模式,我可是聞名已久啊。 

看下面: 

Java代碼  
  1. interface Fruit  
  2. {  
  3.     public void eat();  
  4. }  
  5. class Apple implements Fruit  
  6. {  
  7.     public void eat()  
  8.     {  
  9.         System.out.println("吃蘋果");  
  10.     }  
  11. }  
  12. class Orange implements Fruit  
  13. {  
  14.     public void eat()  
  15.     {  
  16.         System.out.println("吃桔子");  
  17.     }  
  18. }  
  19. class Factory  
  20. {  
  21.     public static Fruit getIns(String classname){  
  22.         Fruit f;  
  23.         f = null;  
  24.         if ("apple".equals(classname))  
  25.         {  
  26.             f = new Apple();  
  27.         }  
  28.         if ("orange".equals(classname))  
  29.         {  
  30.             f = new Orange();  
  31.         }  
  32.         return f;  
  33.     }  
  34. }  
  35.   
  36. public class  Demo6  
  37. {  
  38.     public static void main(String[] args)   
  39.     {  
  40.         Fruit f;   
  41.         if (args[0]!=null){  
  42.         f=Factory.getIns(args[0]);  
  43.             f.eat();  
  44.         }  
  45.         else {  
  46.             System.out.println("請輸入參數");  
  47.         }  
  48.     }  
  49. }  



程式在子類與介面之間加入了一個過渡段,通過過渡段來取得介面的執行個體,這個過渡段就叫做工廠。 

那麼是不是可以這樣理解,工廠就是把主方法提供的東西加工成符合標準的產品(執行個體化對象)以供後面的程式處理呢?

java--物件導向--設計模式--原廠模式

聯繫我們

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