簡單原廠模式

來源:互聯網
上載者:User

  簡單原廠模式的實現。

  假如我的程式中有需要一系列的對象,比如bed,desk,chair…, 要想利用他們,我們就必須在程式中根據使用者要求,然後一個個調用 new 操作符來產生他們,這樣客戶程式就要知道相應的類的資訊,產生的程式碼顯然不夠靈活。再此它們顯然是一類的,都是furniture,既然如此,我們只要一個生產傢具的工廠就可以.我們可以在代碼中不利用具體的類,而只是說明我們需要什麼,然後就能夠得到我們想要的對象.

  先定義一個類,主要聲明一個傢具介面,床和椅子的類:

 

Public interface IFurniture
{}
public class Bed:IFurniture
{
 public Bed()
 {
  Console.WriteLine("I need a bed!");
 }
}
public class Desk:IFurniture
{
 public Desk()
 {
  Console.WriteLine("I need a desk!");
 }
}
public class Chair:IFurniture
{
 public Chair()
 {
  Console.WriteLine("I need a chair!");
 }
}

 

 

 

  再定義一個傢具工廠的類(可以利用反射機制中Type類擷取Name指定的類名的類的Type資訊,然後可以根據這個資訊利用System.Activator建立對象):

 

public class FurnitureFactory
{
 public IFurniture MakeFurniture(string Name)
 {
  IFurniture MyFurniture = null;
  try
  {
   Type type = Type.GetType(Name,true);
   MyFurniture = (IFurniture)Activator.CreateInstance(type);
  }
  catch (TypeLoadException e)
   Console.WriteLine("I dont know this kind of furniture,
      exception caught - {0}" ,e.Message);
   return MyFurniture;
 }
}

 

 

然後在以用戶端進行程式調用:

 

string FurnitureName = Console.ReadLine();
IFurniture MyFurniture;
FurnitureFactory MyFurnitureFactory = new FurnitureFactory();
MyFurniture = MyFurnitureFactory.MakeFurniture(FurnitureName);

 

 

  就這樣預期想實現的,通過這樣就實現了.當然這個例子比較簡單,但是它卻通過原廠模式的思想實現了代碼的靈活性.應用軟體系統開發中,有許多地方可以考 慮使用原廠模式.比如在寫資料層的代碼時候,考慮到程式的可移植性,可拓展性,面向不同的資料庫時,採用原廠模式不為是一件理想的實現方式.

 

聯繫我們

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