Mohammad Rahmani
Mohammad Rahmani

Reputation: 237

Why do we need a factory in factory patterns?

Why do we use simple factory pattern while we can delegate the responsibilty of creating subclasses to the super class?

Upvotes: 0

Views: 89

Answers (1)

Michael Venable
Michael Venable

Reputation: 5051

Generally, your subclasses are aware of the superclass, but your superclass doesn't know anything about the subclasses. The reason for this is to avoid having the superclass dependent on the subclass. Fewer dependencies makes code reuse easier.

Sometimes, it makes things convenient to break that rule and have your superclass be aware of the subclasses and create instances of them, but in other cases it's not possible. For example, when you are creating an extension to a third-party library, you cannot edit the superclass in the library, you must extend it. This is good design, because it prevents their library from being dependent on your extension. On smaller projects, it may not be as important, but on larger projects, avoiding unnecessary dependencies can you reuse a piece of code without dragging in a bunch of unneeded classes with it.

Upvotes: 2

Related Questions