让我感到困惑的是,这篇文章说使用工厂方法而不是简单工厂的动机是要覆盖违反开放封闭原则的行为(检查简单工厂模式问题部分here) 但是在 head first design patterns 书中,这个例子仍然违反了开闭原则,就像这个链接中的图片一样
那么使用工厂方法相对于简单工厂有什么好处呢?
最佳答案
在Factory Patterns - Simple Factory Pattern文章作者写道:
Simple Factory Pattern is not a part of Gang of Four (GoF) book but Factory Method Pattern and Abstract Factory Patterns are part of this standard book.
简单工厂模式 (SFP) 在文章中几乎被描述为 工厂方法模式 (FMP),看起来有点像懒惰开发人员的解决方案。 SFP 只引入了一个类,它创造了所有类型的粉丝。 FMP 为每种风扇类型引入一个工厂。现在,假设在示例控制台应用程序 FanType
中由客户端提供。你将如何实现?无论如何,您都需要创建 switch
或 if-else
对。所以这取决于你把这种代码放在哪里。它看起来像 SFP: is switch
+ new
based on argument.
来自 book below this picture you can find 的另一边:
So, by encapsulating the pizza creating in one class, we now have only one place to make modifications when the implementation changes.
Don’t forget, we are also just about to remove the concrete instantiations from our client code.
因此,回答您的问题:这两个与 Factory Method Design Pattern 中的相同观点及其意图。这取决于您要在哪个级别实现 switch
或 if-else
对。请参阅此示例:Factory Method in Java它被移动到 main 方法的地方。
关于java - 使用工厂方法模式而不是简单工厂的动机是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57901097/