Is factory pattern meaningless in Python?
Asked Answered
F

2

5

Since Python is a duck-typed language is writing factory classes meaningless in Python? http://en.wikipedia.org/wiki/Factory_method_pattern

Fredela answered 18/7, 2011 at 19:29 Comment(0)
H
12

While there may be times when the factory pattern is unnecessary where it may be required in other languages, there are still times when it would be valid to use it - it might just be a way of making your API cleaner - for example as a way of preventing duplication of code that decides which of a series of subclasses to return.

From the Wikipedia article you linked:

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.

All of these can still apply when the language is duck typed.

Hartill answered 18/7, 2011 at 19:41 Comment(1)
You are right. I thought factory pattern is only about the type of object returned from create method of factory class. Obviously the are more reasons to use the pattern when appropriate.Fredela
T
4

It's not exactly a factory class, but the Python standard library has at least one factory method: http://docs.python.org/library/collections.html#collections.namedtuple.

And then, of course, there's the fact that you can create classes dynamically using the type() builtin.

I wouldn't say they're meaningless so much as that Python offers a large amount of possibilities for the sort of factories you can create. It's comparatively simple even to write a factory class that creates factory classes as callable instances of itself.

Thug answered 18/7, 2011 at 19:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.