java設計模式之Factory 方法設計模式

來源:互聯網
上載者:User

標籤:[]   樣本   public   tor   void   post   size   png   多個   

1.定義

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

2.意識圖

 

3.程式碼範例

聯想工廠建立聯想的電腦,戴爾建立戴爾的電腦

1)電腦介面

/** * 電腦介面 * [email protected] *  2017年12月25日 */public interface Computer {    /**     * 描述-->一句話簡介     * @param description  描述語     */    public void describe(String description);}

 

2).戴爾電腦

/** * Dell電腦 * [email protected] *  2017年12月25日 */public class DellComputer implements Computer {    @Override    public void describe(String description) {        System.out.println(description);    }    }

 

3).聯想電腦

/** * Lenovo電腦 * [email protected] *  2017年12月25日 */public class LenovoComputer implements Computer {    @Override    public void describe(String description) {        System.out.println(description);    }    }

 

4).電腦工廠

/** * 電腦工廠 * [email protected] *  2017年12月25日 */public class ComputerFactory {    public static Computer buildComputer(String pcName) {        if("dell".equalsIgnoreCase(pcName)) return new DellComputer();        if("lenovo".equalsIgnoreCase(pcName)) return new LenovoComputer();        return null;    }}

 

5).電腦操作類

/** * 電腦操作類,調用工廠建立電腦 * [email protected] *  2017年12月25日 */public class ComputerOperator {        /**     * 建立電腦     * @param pcName  電腦名字     * @param  description  電腦描述     */    public void createComputer(String pcName,String description) {        ComputerFactory.buildComputer(pcName).describe(description);    }}

 

6).用戶端類

/** * 用戶端 * [email protected] *  2017年12月25日 */public class Client {    public static void main(String[] args) {        ComputerOperator computerOperation = new ComputerOperator();        computerOperation.createComputer("lenovo", "我是聯想");        computerOperation.createComputer("dell", "我是戴爾");    }}

 

 

7).結果

我是聯想我是戴爾

 

 

4.總結

何時選用?

1).一個介面多個實現,但是又不知道具體用哪一個實現,由子類去指定

2).系統設計本身就由子類去指定實作類別

 

java設計模式之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.