簡單工廠模式

簡單工廠模式:定義一個工廠類,根據(jù)參數(shù)不同返回不同的類的實(shí)例, 被創(chuàng)建的實(shí)例通常都有共同的實(shí)例 ; 適用于創(chuàng)建對象比較少的場景

示例代碼:

public class Factory {
    
    public Fruit factoryMehtod(String arg) {
        if (arg.equals("apple")) {
            return new Apple();
        } else if (arg.equals("peach")) {
            return new Peach();
        }
        return null;
    }
}

public abstract class Fruit {
    // 水果名字
    String name;
}

public class Apple extends Fruit {

    public Apple() {
        super();
        // TODO Auto-generated constructor stub
        System.out.println("生產(chǎn)蘋果");
    }
    
}


public class Peach extends Fruit {

    public Peach() {
        super();
        // TODO Auto-generated constructor stub
        System.out.println("生產(chǎn)peach");
    }
    
}

public class Client {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Factory factory = new Factory();
        
        // 選擇生成蘋果
        factory.factoryMehtod("apple");
        // 選擇生成桃子       
        factory.factoryMehtod("peach");
    }

}

UML圖例:


簡單工廠模式.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容