Next creational pattern that we will have a closer look at – is Factory pattern. There are at least two different Factory patterns, Factory method and Abstract Factory. In this installment we will be looking at the Factory method pattern.

- Image via Wikipedia
The Factory method pattern deals with creating objects without specifying the exact class of the object that will be created. Pattern defines separate methods for creating objects, whose subclasses can be overridden to specify the derived type of the product that factory will create. It is basically any method whose purpose is creation of the objects.
Factory method pattern is used to encapsulate the creation of objects. When this process is complex or is not simple to understand, than it is prudent to use factory method pattern in your design. Pattern is useful if you are writing a toolkit of framework code where you want to encapsulate the creation of toolkit or framework specific objects. You will definitely benefit from factory methods when you have parallel class hierarchy between objects, because one type of objects will have to be able to create objects from other type. There is where encapsulated factory method becomes handy. You will come in contact with this pattern with the applications that are unit tested. More precisely in applications that use test driven development as a base for their development cycle.
Well I think it is time for some examples. As the name of our post tells us we will create a factory method which will produce fungi. If we look at the UML our Product will be replaced with Fungus. Our ConcreteCreator and Creator will be replaced with FungusFactory. Method called factoryMethod will be replaced with create method. Now let’s create some fungus in Java.
public class FungusFactory {
private static FungusFactory instance;
public enum FungusFamily {
Microsporidia,
Chytridiomycota,
Zoopagomycotina
}
public interface Fungus {
public String getFamily();
}
public class MicrospordiaFungus implements Fungus {
private String family = "Microsporidia";
public String getFamily() { return family; }
}
public class ChytridiomycotaFungus implements Fungus {
private String family = "Chytridiomycota";
public String getFamily() { return family; }
}
public class ZoopagomycotinaFungus implements Fungus {
private String family = "Zoopagomycotina";
public String getFamily() { return family; }
}
public static synchronized Fungus create(FungusFamily _family) {
if (instance == null)
instance = new FungusFactory();
switch (_family) {
case Microsporidia:
return instance.new MicrospordiaFungus();
case Chytridiomycota:
return instance.new ChytridiomycotaFungus();
case Zoopagomycotina:
return instance.new ZoopagomycotinaFungus();
}
throw new IllegalArgumentException("This factory can't " +
"make fungus of unknown family [" + _family + "]") ;
}
public static void main(String [] argv) {
Fungus microsporidiaFungus =
FungusFactory.create(FungusFactory.FungusFamily.Microsporidia);
System.out.println(microsporidiaFungus.getFamily());
}
}
In PHP:
class FungusFactory {
static function create($family) { // As of PHP 5.3.0
switch ($family) {
case 'Microsporidia': return new MicrosporidiaFungus();
case 'Chytridiomycota': return new ChytridiomycotaFungus();
case 'Zoopagomycotina': return new ZoopagomycotinaFungus();
}
}
interface Fungus {
function getFamily();
}
class MicrosporidiaFungus implements Fungus {
function getFamily() { return 'Microsporidia'; }
}
class ChytridiomycotaFungus implements Fungus {
function getFamily() { return 'Chytridiomycota'; }
}
class ZoopagomycotinaFungus implements Fungus {
function getFamily() { return 'Zoopagomycotina'; }
}
function test() {
echo FungusFactory::create('Microsporidia')->getFamily();
}In python:
class FungusFactory:
def create( self, family ):
if family == "Microsporidia":
return MicrospordiaFungus()
elif family == "Chytridiomycota":
return ChytridiomycotaFungus()
elif family == "Zoopagomycotina":
return ZoopagomycotinaFungus()
else:
return Fungus()
create = staticmethod(create)
class Fungus:
def getFamily( self ): raise NotImplementedError
class MicrospordiaFungus( Fungus ):
def getFamily( self ): return "Microsporidia"
class ChytridiomycotaFungus ( Fungus ):
def getFamily( self ): return "Chytridiomycota"
class ZoopagomycotinaFungus ( Fungus ):
def getFamily( self ): return "Zoopagomycotina"
if __name__ == "__main__":
print FungusFactory.create("Microsporidia").getFamily()
In C++:
Header:
class Fungus {
public:
virtual std::string getFamily() = 0;
};
class MicrosporidiaFungus: public Fungus {
public:
std::string getFamily();
};
class ChytridiomycotaFungus: public Fungus {
public:
std::string getFamily();
};
class ZoopagomycotinaFungus: public Fungus {
public:
std::string getFamily();
};
class FungusFactory {
public:
static const int MICROSPORIDIA = 1;
static const int CHYTRIDIOMYCOTA = 2;
static const int ZOOPAGOMYCOTINA = 3;
static Fungus* create(int type);
};
Source:
#include "factory.hpp"
Fungus* FungusFactory::create(int family)
{
switch (family)
{
case FungusFactory::MICROSPORIDIA:
return new MicrosporidiaFungus();
break;
case FungusFactory::CHYTRIDIOMYCOTA:
return new ChytridiomycotaFungus();
break;
case FungusFactory::ZOOPAGOMYCOTINA:
return new ZoopagomycotinaFungus();
break;
}
throw new std::string("This factory can't make fungus of unknown family");
}
std::string MicrosporidiaFungus::getFamily()
{
return std::string("Microsporidia");
}
std::string ChytridiomycotaFungus::getFamily()
{
return std::string("Chytridiomycota");
}
std::string ZoopagomycotinaFungus::getFamily()
{
return std::string("Zoopagomycotina");
}
int main(int argc, char *argv[])
{
std::cout << FungusFactory::create(FungusFactory::MICROSPORIDIA)->getFamily() << std::endl;
}
Now as with singleton there are some drawbacks from using the factory method pattern. If you are re-factoring existing code you should watch out for your client classes which you will break in process. All instances of object creation that you will replace by factory methods must be replaced with factory method calls. Now if you have an application that creates a lot of objects in the code you have your work cut out for you. The factory method relays on private constructor, hence it can not be extended. If we by any chance make the constructor protected or even good forbid public and somehow are able to extend the existing factory, the extended factory must re-implement all the factory methods defined in base factory.
This is all the juice we have for today. Next week we will look at another factory pattern. That one will have more abstraction in it.
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=ee3e6dd9-1efd-4dcd-832f-0802e2da9384)


[...] previous article we have talked about factory pattern. We have learned that factory pattern deals with creation of [...]