Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should the factory pattern be used?

Just as the title asks, when should a trigger in your head go off signifying "Aha! I should use the factory pattern here!"? I find these moments will occur with many other design patterns, but never do I stop myself and think about this pattern.

like image 423
Chris Avatar asked Dec 02 '22 07:12

Chris


2 Answers

Whenever you find yourself with code that looks something like this, you should probably be using a factory:

IFoo obj;
if ( someCondition ) {
   obj = new RegularFoo();
} else if ( otherCondition ) {
   obj = new SpecialFoo();
} else {
   obj = new DefaultFoo();
}
like image 186
Eric Petroelje Avatar answered Dec 10 '22 01:12

Eric Petroelje


The factory pattern is best employed in situations where you want to encapsulate the instantiation of a group of objects inside a method.

In other words, if you have a group of objects that all inherit from the same base class or all implement the same interface that would be an instance where you would want to use the factory pattern (that would be the "pattern" you would look for).

like image 38
Andrew Hare Avatar answered Dec 10 '22 01:12

Andrew Hare