Advantages and disadvantages of factory pattern

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
srikanth03565
Forum Newbie
Posts: 10
Joined: Sat Jul 16, 2011 12:13 am

Advantages and disadvantages of factory pattern

Post by srikanth03565 »

Hi
Can any one explain advantages and disadvantages of factory pattern.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Advantages and disadvantages of factory pattern

Post 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.
(#10850)
User avatar
sweatje
Forum Contributor
Posts: 277
Joined: Wed Jun 29, 2005 10:04 pm
Location: Iowa, USA

Re: Advantages and disadvantages of factory pattern

Post 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 :)
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Advantages and disadvantages of factory pattern

Post 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.
Post Reply