設計模式-簡單工廠模式

設計模式-簡單工廠模式

簡單工廠模式(Simple Factory Pattern),又叫靜態工廠方法模式(Static Factory Method Pattern)

簡單工廠模式定義: 提供創建對象的接口,通常這些對象具有相同的類型。

對象具有相同的類型什麼意思?我們不妨先來看簡單工廠模式UML圖
SimpleFactory

PC(個人電腦)是基類
Dell和IBM電腦繼承了基類PC,他們都具有相同的類型,來自同一個基類(父類)。

如何運用呢?通常我們是這樣創建對象比如Dell dell=new Dell() ,現在我們把這個過程封裝到Factory中,
讓Factory去幫我們完成這個創建工作。下面我們來看下具體的示例代碼。

//抽象類
abstract class PC
{
    private string name;

    public PC(string name)
    {
        this.name = name;
    }

    public virtual string Name { get { return name; } set { name = value; } }
    public abstract void Describe();
}

//Dell具體類,繼承基類PC
class Dell : PC
{
    public Dell(string name) : base(name)
    {

    }

    public override void Describe()
    {
        System.Console.WriteLine("I am {0} personal computer", Name);
    }
}

//IBM具體類,繼承基類PC
class IBM : PC
{
    public IBM(string name) : base(name)
    {

    }

    public override void Describe()
    {
        System.Console.WriteLine("I am {0} personal computer", Name);
    }
}

//工廠類,用於實例化各子類對象
class Factory
{
    static PC pc;//定義基類對象

    //看到面向接口編程了吧,Create方法返回的就是基類PC類型,而不是具體的Dell或IBM類
    public static PC Create(string name)
    {
        if (name == "Dell")
            pc = new Dell(name);//創建Dell對象
        else if (name == "IBM")
            pc = new IBM(name);//創建IBM對象
        else
            throw new NullReferenceException("object name error: " + name);
        return pc;
    }
}

具體調用代碼

            PC dell = Factory.Create("Dell");
            //pc = Factory.Create("xxDell")//這個調用將出錯
            dell.Describe();
            dell.Name = "OtherDell";
            dell.Describe();

            System.Console.WriteLine();

            PC ibm = Factory.Create("IBM") ;  
            ibm.Describe();
            ibm.Name = "OtherIBM";
            ibm.Describe();

正確的調用方式
PC dell = Factory.Create(“Dell”);
這裏寫圖片描述

這樣調用將出錯
pc = Factory.Create(“xxDell”)
這裏寫圖片描述

簡單工廠模式
優點:使用時不需要創建對象,統一由工廠創建。
缺點:必須知道要創建的具體對象的名稱。

版權所有,轉載請註明文章出處 http://blog/csdn.net/cadenzasolo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章