Factory 方法模式

來源:互聯網
上載者:User

標籤:

思考問題:一個工廠生產汽車,在不知道具體工廠和具體汽車品牌時應該如何設計?
答案:Factory 方法模式。定義一個工廠介面和汽車介面,然後在工廠介面中聲明一個factoryFactory 方法,傳入參數用於決定需要生產的汽車的類型。

聲明汽車工廠介面:

package com.shusheng.factoryMethodModel;/**抽象工廠*/public interface CarFactoryI {    //Factory 方法,建立一個汽車對象,其輸入參數類型自行設定    public <T extends CarI> T factory(Class<T> c);}

聲明汽車介面:

package com.shusheng.factoryMethodModel;public interface CarI {}

定義汽車工廠實作類別:

package com.shusheng.factoryMethodModel;/**具體的googleCar工廠*/public class GoogleCarFactory implements CarFactoryI {//生產汽車    @Override    public <T extends CarI> T factory(Class<T> c) {        CarI carI = null;        try {            //carI = (CarI) Class.forName(c.getName()).newInstance();//顯示載入class檔案,兩種方式都可以            carI = c.newInstance();//隱式載入class檔案        } catch (Exception e) {            e.printStackTrace();        }        return (T) carI;    }}

定義具體汽車類:
平治類:

package com.shusheng.factoryMethodModel;public class BMW implements CarI {}

寶馬類:

package com.shusheng.factoryMethodModel;public class Benz implements CarI {}

測試程式:

package com.shusheng.factoryMethodModel;public class FactoryMethodTest {    public static void main(String[] args) {        CarFactoryI factoryI = new GoogleCarFactory();        Benz benz = factoryI.factory(Benz.class);//生產平治        System.out.println(benz);//平治        BMW bmw = factoryI.factory(BMW.class);//生產寶馬        System.out.println(bmw);//寶馬    }}

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.