带有构造函数参数的抽象工厂模式

问题描述 投票:0回答:1

我有以下两种使用抽象工厂模式的方式

方法1

abstract class Dough {
 def getDoughType: String
}

abstract class Sauce {
 def getSauceType: String
}

abstract class AbstractIngredientsFactory {
 def createDough: Dough
 def createSauce: Sauce
}

class ThinDough extends Dough {
  def getDoughType: String = "Thin Dough !!!"
}

class RedSauce extends Sauce {
  def getSauceType: String = "Red Sauce !!!"
}

class ChicagoStoreIngredientsFactory extends AbstractIngredientsFactory {
  def createDough: Dough = new ThinDough
  def createSauce: Sauce = new RedSauce
}

方法2

 //no longer seems like a factory
 case class IngredientsFactory(dough: Dough, sauce: Sauce)

 // concrete instance
 val chicagoIngrediendtsFactory = new IngredientsFactory(new ThinDough, new RedSauce)

方法2虽然不再类似于标准工厂,但似乎具有封装特定成分以供特定商店使用的相同目的。但是方法2取决于组成,我不需要为每个区域创建实现。

方法2是否是反模式?

scala inheritance factory composition factory-pattern
1个回答
2
投票

方法2不是工厂模式,但这并不会使它成为反模式。 IngredientsFactory不会创建任何内容,只是一个容器,可以称为Recipe

关键区别在于,方法1在工厂内部生成原料,而方法2从外部注入原料。方法1允许芝加哥商店使用秘密食谱来生成食材,而方法2则需要芝加哥商店让所有人都知道成分是什么。

选择取决于应用程序,但对与错。


还请注意,方法1中的此代码将无法编译:

def createDough: Dough = new ThinDough
def createSauce: Sauce = new RedSauce

应该是

val createDough: Dough = ThinDough
val createSauce: Sauce = RedSauce
© www.soinside.com 2019 - 2024. All rights reserved.