工厂模式在Python中没有意义吗?

2024-04-18 13:51:10 发布

您现在位置:Python中文网/ 问答频道 /正文

既然Python是一种duck类型的语言,那么用Python编写工厂类是没有意义的吗? http://en.wikipedia.org/wiki/Factory_method_pattern


Tags: org语言http类型factory工厂wikiwikipedia
2条回答

它并不完全是一个factory,但是Python标准库至少有一个factory方法:http://docs.python.org/library/collections.html#collections.namedtuple。在

当然,还有一个事实,您可以使用the ^{} builtin动态创建类。在

我不会说它们毫无意义,因为Python为您可以创建的工厂提供了大量的可能性。即使编写一个工厂类来创建工厂类作为其自身的可调用实例,也相对简单。在

虽然有时工厂模式在其他语言中可能是不必要的,但仍然有使用它是有效的——它可能只是使API更干净的一种方法——例如,作为防止代码重复的一种方法,它决定返回一系列子类中的哪一个。在

从你链接的维基百科文章中:

Use the factory pattern when:

  • The creation of the object precludes reuse without significantly duplicating code.
  • The creation of the object requires access to information or resources not appropriate to contain within the composing object.
  • The lifetime management of created objects needs to be centralised to ensure consistent behavior.

当语言是duck类型时,所有这些仍然适用。在

相关问题 更多 >