2012-03-13 66 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>();