2012-03-13 65 views
0

我正在做一些關於設計模式實現變體的研究,我遇到並閱讀了一些在此實現的示例http://www.codeproject.com/Articles/37547/Exploring-Factory-Patternhttp://www.oodesign.com/factory-pattern.html。我關注的焦點是在沒有反思的情況下實施工廠模式。所陳述的文章說,我們需要註冊的對象不是類,這似乎罰款和邏輯給我,但看到了實現的時候,我看到的方法RegisterProduct用於自registeration例如,在代碼的物體的下面無反射的工廠模式實現

// Factory pattern method to create the product 
public IRoomType CreateProduct(RoomTypes Roomtype) 
{ 
    IRoomType room = null; 
    if (registeredProducts.Contains(Roomtype)) 
    { 
     room = (IRoomType)registeredProducts[Roomtype]; 
     room.createProduct(); 
    } 
    if (room == null) { return room; } 
    else { return null; } 
} 

// implementation of concrete product 
class NonACRoom : IRoomType 
{ 
    public static void RegisterProduct() 
    { 
     RoomFactory.Instance().RegisterProduct(new NonACRoom(), RoomTypes.NonAcRoom); 
    } 
    public void getDetails() 
    { 
     Console.WriteLine("I am an NON AC Room"); 
    } 
    public IRoomType createProduct() 
    { 
     return new NonACRoom(); 
    } 
} 

重複,我們必須在創建工廠對象之前調用它,也就是在客戶的主要類中的某個地方或確保其調用的任何適用的任何地方之前。下面是我們正在創建一個新產品,並在上面的方法中,我們正在創造一個似乎沒有意義的新產品。任何機構對此的評論

回答

0

第一次創建是用來給RegisterProduct工作。可能,該對象的成本是可以忽略的。它在初始化過程中完成,並不重要。

這個實例是必需的,因爲在C#中你需要一個對象來調用createProduct。這是因爲您不能使用反射來存儲對類型的引用,而不是對對象的引用。

+0

我很抱歉,我不能讓你多。你能否詳細說明一下。我看到爲同一件事物創建了兩個對象,如果我們有一個散列圖並且我們已經註冊了這個對象,爲什麼我們應該重用它而不是創建它 – 2012-03-13 07:56:53

+0

因爲工廠模式是爲了創建** NEW **對象。在工廠模式中,最終目標是創建許多對象。在這種特殊情況下,您需要第一個實例,然後使用第一個實例創建許多新實例。 'createProduct'通常在這樣的應用程序中被稱爲數千次。 – 2012-03-13 07:59:06

+0

對我來說很有意義 – 2012-03-13 08:00:33

0

我在過去做過類似的事情。實際上,這就是我想出了(並且也與整個「類型」枚舉做掉):

public interface ICreator 
{ 
    IPart Create(); 
} 


public interface IPart 
{ 
    // Part interface methods 
} 


// a sample creator/part 

public PositionPartCreator : ICreator 
{ 
    public IPart Create() { return new PositionPart(); } 
} 

public PositionPart : IPart 
{ 
    // implementation 
} 

現在我們有工廠本身:

public sealed class PartFactory 
{ 
    private Dictionary<Type, IPartCreator> creators_ = new Dictionary<Type, IPartCreator>(); 

    // registration (note, we use the type system!) 
    public void RegisterCreator<T>(IPartCreator creator) where T : IPart 
    { 
     creators_[typeof(T)] = creator; 
    } 


    public T CreatePart<T>() where T: IPart 
    { 
     if(creators_.ContainsKey(typeof(T)) 
      return creators_[typeof(T)].Create(); 
     return default(T); 
    } 
} 

這本質上與需要摒棄爲「類型」枚舉,並使事情真的很容易:

PartFactory factory = new PartFactory(); 
factory.RegisterCreator<PositionPart>(new PositionPartCreator()); 
// all your other registrations 



// ... later 


IPart p = factory.CreatePart<PositionPart>();