Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the advantage of factory pattern? [duplicate]

Possible Duplicate:
What are the practical uses of Factory Method Pattern?
Differences between Abstract Factory Pattern and Factory Method

My current understanding of factory is that it can create object by a input string, say

Factory.create("mouse");
Factory.create("hamster");

What's the advantage of this pattern over new?

like image 942
Adam Lee Avatar asked Feb 04 '12 13:02

Adam Lee


2 Answers

It's better to create a factory when you need to create complex products (i.e. "encapsulate" a complex product creation process), have a single point of control for multiple products, or need to manage the lifetime and/or resources that these products consume from a single point of reference. In some cases it is too complicated to rewrite product instantiation and handling code with "new", so the factory method ensures reuse and uniformity while minimising potential coding errors.

An example might be say in a visual programming IDE where you are using a toolkit in 2 or more projects open at the same time; the toolkit and it's features would most likely be instantiated by a factory pattern because it is so complex graphically and logically, and it requires careful management of one or more of its instances.

like image 67
Fuzzy Analysis Avatar answered Sep 21 '22 22:09

Fuzzy Analysis


A factory is useful if you want to "harmonize" the creation of different objects (in your example Mouse and Hamster) through a shared Factory. This can be used to (a) abstract away specific Constructor-details for each subclass of a common super class (e.g. Animal in your example) or (b) providing default arguments to a Constructor depending on which type of object (or animal) is to be created.

It can be used to unify the creation of objects sharing a commonality, e.g. in caching: CacheFactory -> Memcache, Filecache, ... Working with each cache is similar, but setting up different caching strategies may differ vastly. When using the factory method you can switch between different caching strategies more easily, at best by just chaning one line of code factory("Memcache", options),without having to worry about the intricacies of the specific backend;

like image 31
dbrumann Avatar answered Sep 19 '22 22:09

dbrumann