这种工厂方法的创建模式? [英] Is this Factory Method creation pattern?
问题描述
我一直在使用工厂方法创建模式。我刚才被告知这样:
I have been using factory method creation pattern for awhile now. I was just recently told that this:
public static class ScheduleTypeFactory
{
public static IScheduleItem GetScheduleItem(ScheduleTypeEnum scheduleType)
{
IScheduleItem scheduleItem = null;
switch (scheduleType)
{
case ScheduleTypeEnum.CableOnDemandScheduleTypeID:
{
scheduleItem = new VODScheduleItem();
break;
}
case ScheduleTypeEnum.BroadbandScheduleTypeID:
{
scheduleItem = new VODScheduleItem();
break;
}
case ScheduleTypeEnum.LinearCableScheduleTypeID:
{
scheduleItem = new LinearScheduleItem();
break;
}
case ScheduleTypeEnum.MobileLinearScheduleTypeID:
{
scheduleItem = new LinearScheduleItem();
break;
}
}
return scheduleItem;
}
}
不是我的技术的工厂方法创建模式没有告诉我为什么或给我她的解释。我请求解释,她告诉我,她没有时间。我被告知要重命名它。如果我错了,那么我无疑会接受这个错误地实施了这么多年了。这是怎么实现工厂方法创建模式?感谢提前。
is not a factory method creation pattern by my "Tech" lead without telling me why or giving me her interpretation. I kindly asked for an explanation and she told me she didn't have time. I was told to just rename it. If I am wrong, then I will no doubt accept that I have implemented this incorrectly for years. Is this how YOU would implement the factory method creation pattern? Thanks in advance.
推荐答案
我同意将方法称为工厂方法,虽然设计不是严格的工厂方法模式
这是一个关键点(维基百科):
I would agree to call the method a "Factory Method", though the design is not strictly a "Factory Method Pattern".
Here is a key point (from Wikipedia):
...工厂方法让一个类将实例化推迟到子类。
...The Factory method lets a class defer instantiation to subclasses."
由于你的类是静态的,方法的静态(因此是非虚拟的),没有推迟可能。
Since your class is static and method static (hence non-virtual), there is no "deferring" possible.
从概念上说,这个实现虽然提供了封装,但并没有解耦/延迟任何决定。
Conceptually, notice also, that this implementation, though provides encapsulation, does not decouple/delay any decision.
说完了,同样的维基百科文章将这个模式呈现为工厂方法模式的变体。
Having said that, same Wikipedia article does present this schema as a variant of the "Factory Method Pattern".
总结摘要:在我看来,这个代码片段不是Factory Method OO Design Pattern的 实现,因为它不能满足将子类推迟到子类的实例化。虽然个人我可以自由地将这个解决方案称为工厂方法。
Summary of the Summary: In my opinion this snippet is not a proper implementation of the "Factory Method OO Design Pattern", since it does not satisfy "a class defer instantiation to subclasses." Though, personally I would freely refer to this solution as "factory method".
要使其真正的工厂方法模式,您需要允许该方法被子类覆盖。即工厂类(ScheduleTypeFactory)需要扩展(即非静态),GetScheduleItem需要是虚拟的。
To make it real factory method pattern, you need to allow the method to be overridden by subclasses. I.e. factory class (ScheduleTypeFactory) needs to be extensible (i.e. non-static), and GetScheduleItem needs to be virtual.
这篇关于这种工厂方法的创建模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!