Page 1 of 1
Advantages and disadvantages of factory pattern
Posted: Sun Aug 07, 2011 12:27 pm
by srikanth03565
Hi
Can any one explain advantages and disadvantages of factory pattern.
Re: Advantages and disadvantages of factory pattern
Posted: Sun Aug 07, 2011 8:29 pm
by Christopher
I think my problem with a Factory is that it create the false sense of adding flexibility while it only seems to add complexity. Where I have implemented them I have eventually removed them.
Re: Advantages and disadvantages of factory pattern
Posted: Fri Sep 09, 2011 11:35 am
by sweatje
The main point of the Factory Pattern in PHP application is to centralize the creation logic to one location. If you simply do new ClassName everywhere, then you have hard coded that into your application and you have to locate and change every instance whenever you would need to change it in the future. If instead you encapsulate this somehow (function, class method, factory object) then you have a single location in your code where you can change this creation logic without affecting the other parts of your code.
The decision to use the pattern is similar to any other design pattern: does the problem you are trying to solve, for which the design pattern is a time tested solution, actually exist in your code? If not, you could be adding unnecessary complexity to your code base for flexibility you will never need. See the YAGNI principal

Re: Advantages and disadvantages of factory pattern
Posted: Fri Sep 09, 2011 4:32 pm
by John Cartwright
Factories play an important role in libraries with lots of dependencies. As sweatje put it, by implementing the factory pattern we can centralize the creation of the object, which understands how to build it in a ready to use state with it's dependencies. With that said, we can much more easily manage and mock factories than manually managing them in the underlying code itself several times over.