Php – Should I use the factory design pattern for every class

constructiondesign-patternsPHPwebsites

I've been writing a website in PHP. As the code becomes more complex, I keep finding problems that can be solved using the factory design pattern. For example: I've a got a class Page which has subclasses HTMLPage, XMLPage, etc. Depending on some input I need to return an object of either one of these classes. I use the factory design pattern to do this.

But as I encounter this problem in more classes, I keep having to change code which still initiates an object using its constructor. So now I'm wondering: is it a good idea to change all code so that it uses the factory design pattern? Or are there big drawbacks?

I'm currently in a position to change this, so your answers would be really helpful.

Best Answer

Of course not.

The factory pattern is useful if you need to encapsulate create-time polymorphism from consumers, that is, you want to provide a transparent point from which new instances of a polymorphic type are created.

If the type in question is not polymorphic, the factory pattern is pointless.

If a single point of creation doesn't make sense, neither does the factory pattern.

If it is undesirable to hide the polymorphism details away, the factory pattern is probably inappropriate, too.

As with anything that adds complexity, you should default to not using it, but spot the point at which it is beneficial early on and apply it before it is too late.

Also, consider this: If you use a factory for everything, who creates the factory? Another factory? And who creates that?