Factory Pattern
The post #2 was supposed to be talking about the factory pattern but since we left a very important categorization of patterns, talking about that in last post was a good thing. Now lets just talk about factory pattern now.
As from the name it is quite clear that here we are going to create an object which is going to serve as a factory for creating other objects. So according to design gurus the factory pattern is
• Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Oooh, that was a bit hard, even I am not even able to understand that fully, so lets do a little post mortem here.
‘Define an interface of creating an object’ – Every system that want to create any object know how that object should be created but it may not know exactly the type of objects it want to create.
For example, Lets say if we are about to start a business of producing cars. We have set up a small firm and now we want to establish our factory to produce cars. We are still waiting for an order, as we are an outsourcing company in manufacturing cars.
Since we have no specific orders we cannot create any cars but we know that creating a car requires same steps like creating the frame, then creating seats, creating tyres. But the specifics of these things can differ from car to car. Fair enough, lets have an interface for this factory ready with these operations and once we get an order we will just go and start implementing the specific factory implementing this interface. So lets create the interface
class ICarFactory
{
protected:
ICarFactory(void);
//Methods that may vary for different cars
virtual void CreateFrame() = 0;
virtual void CreateTyre() = 0;
virtual void CreateSeat() = 0;
public:
~ICarFactory(void);
static ICarFactory* GetCarFactory();
//factory method to create a car
virtual car* CreateCar() = 0;
};
Here we have an interface with all the functionalities required to be created. Along with that we have a function which will just create the car using these functions and give it to the sales department.
But wait, there is one question here, why function GetCarFactory(), well we will be using the virtual construction mechanism to create the factories. Wait I am coming on that.
Now we have covered the first part that we have an interface ready for creating object, in our case cars.
But this is just the one part of it. We know that we want to create cars and car is also an object. I know, I know we still didn’t get any orders for cars but so what, the facts that all the cars have similar behavior doesn’t change. So what I want to say here is that we can also define an interface for our product, which is car so let us just do and define that interface also.
class Icar
{
public:
~Icar(void);
static Icar* Create();
//Some functions that a car should have like
virtual void openDoor();
virtual void enableMods();
protected:
Icar(void);
};
The reason why the canstrustor is protected is also the virtual construction mechanism, which I am gonna explain in a minute just bear it for some time.
Now we have and factory interface and a product interface with us and we are all set for accepting any orders.
Good news buddy, the toyota company has just called you and want you to produce cars. Now comes the time that we were waiting from so long. Now we have all the basic interfaces in place first thing we will do is we will create a concrete car factory.
class CarFactory :
public ICarFactory
{
private:
CarFactory(void);
//Methods that may vary for different cars
void CreateFrame(){/* Some imlementation*/};
void CreateTyre(){/* Some imlementation*/};
void CreateSeat(){/* Some imlementation*/};
static ICarFactory *instance;
public:
virtual ~CarFactory(void);
static ICarFactory* GetCarFactory()
{
if(0 == instance)
{
instance = new CarFactory;
}
return instance;
}
Icar* CreateCar(){/*Wait we will do something here to create the car*/};
};
//static member variables definition
ICarFactory * CarFactory::instance = 0;
Now carefully observe this factory we have just created. What we have done is that we have implemented all the methods from the ICarafctory interface that are required to create a car. We have implemented a method which will actually create a car, i.e. CreateCar(). And the function GetCarFactory() to return the car factory
The member variable instance is to make the class a singleton. Well we are creating a factory to create the cars bit does it really make sense to have a lot of factories floating around in the application. Probably not, so I thought of making it singleton.
Now let me explain a little bit about the function GetCarFactory and CreateCar, since they are also defined in the interface and returning ICarFactory* and ICar* respectively. Well this is what is called as virtual construction.
See what we are doing is we are making an interface and making its constructor protected. Now this class can only be inherited. We also define a method called GetCarFactory returning ICarFactory* and made it static.
Now The CarFactory is implementing this interface so it implemented this function. Now inside this class we will make the constructor private, so the only way to create a factory will be using this function only. Now in this function we will create a type CarFactory and return its pointer.
The benefit from this that, if we have multiple factories, the application need not keep a track of these factories remember ‘but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.’.
The application now will just keep ICarFactory with it and create the concrete factories like
ICarFactory* factory = CarFactory::GetCarFactory();
Now here the application has pointer to the ICarFactory and it is leting the subclass cretae its obbject. Virtual construction isn’t it.
Same is that case with ICar interface. The ICar has a Create function returning ICar*. So lets just write our toyoya which implements this function.
class toyota : public Icar
{
public:
~toyota(void){};
static car* Create()
{
return new toyota();
}
//Some functions that a car should have like
virtual void openDoor(){/*Some implenmentation*/};
virtual void enableMods(){/*Some implenmentation*/};
private:
toyota(void){};
};
Now if we want to create a car we just can use ICar* to create the car. In our case the CarFactory wants to create this car so lets just put this car creation in place.
class CarFactory :
public ICarFactory
{
private:
CarFactory(void);
//Methods that may vary for different cars
void CreateFrame(){/* Some imlementation*/};
void CreateTyre(){/* Some imlementation*/};
void CreateSeat(){/* Some imlementation*/};
static ICarFactory *instance;
public:
virtual ~CarFactory(void);
static ICarFactory* GetCarFactory()
{
if(0 == instance)
{
instance = new CarFactory;
}
return instance;
}
Icar* CreateCar()
{
car *c = toyota::Create();
return c;
};
};
//static member variable definition
ICarFactory * CarFactory::instance = 0;
Here we can see in create car function we have again utilized the virtual construction mechanism and used Icar* to create the Toyota.
Now we have all the code in place. Don’t you believe me. Well look at the code and we are all done. Now what our sales department needs to do is the question. I mean what should be done to use the factory and produce a car.
ICarFactory* factory = CarFactory::GetCarFactory();
car *myCar = factory->CreateCar();
that’s it and myCar contains a toyota.
Now let us try to visualize the factory pattern and map our implementation with it.

Our ICarFactory corresponds to Creator, Product Corrspond to ICar, Toyota corresponds to ConcreteProduct and CarFactory is ConcreteCreator. Now it looks like we have successfully implemented the factory pattern.
Now we know know how to implement the factory pattern lets just try to find its applicability.
Use the Factory Method pattern when
• a class can't anticipate the class of objects it must create.
• a class wants its subclasses to specify the objects it creates.
• classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
Well this is the basic implementation of the factory pattern. We will discuss the various versions of this pattern and there pros and cons some other time, but to understand the factory pattern I have followed a reverse approach. i.e. first code then understand and it worked for me. I hope this article will be a little useful for understanding the factory pattern in a C++ way.
The post #2 was supposed to be talking about the factory pattern but since we left a very important categorization of patterns, talking about that in last post was a good thing. Now lets just talk about factory pattern now.
As from the name it is quite clear that here we are going to create an object which is going to serve as a factory for creating other objects. So according to design gurus the factory pattern is
• Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Oooh, that was a bit hard, even I am not even able to understand that fully, so lets do a little post mortem here.
‘Define an interface of creating an object’ – Every system that want to create any object know how that object should be created but it may not know exactly the type of objects it want to create.
For example, Lets say if we are about to start a business of producing cars. We have set up a small firm and now we want to establish our factory to produce cars. We are still waiting for an order, as we are an outsourcing company in manufacturing cars.
Since we have no specific orders we cannot create any cars but we know that creating a car requires same steps like creating the frame, then creating seats, creating tyres. But the specifics of these things can differ from car to car. Fair enough, lets have an interface for this factory ready with these operations and once we get an order we will just go and start implementing the specific factory implementing this interface. So lets create the interface
class ICarFactory
{
protected:
ICarFactory(void);
//Methods that may vary for different cars
virtual void CreateFrame() = 0;
virtual void CreateTyre() = 0;
virtual void CreateSeat() = 0;
public:
~ICarFactory(void);
static ICarFactory* GetCarFactory();
//factory method to create a car
virtual car* CreateCar() = 0;
};
Here we have an interface with all the functionalities required to be created. Along with that we have a function which will just create the car using these functions and give it to the sales department.
But wait, there is one question here, why function GetCarFactory(), well we will be using the virtual construction mechanism to create the factories. Wait I am coming on that.
Now we have covered the first part that we have an interface ready for creating object, in our case cars.
But this is just the one part of it. We know that we want to create cars and car is also an object. I know, I know we still didn’t get any orders for cars but so what, the facts that all the cars have similar behavior doesn’t change. So what I want to say here is that we can also define an interface for our product, which is car so let us just do and define that interface also.
class Icar
{
public:
~Icar(void);
static Icar* Create();
//Some functions that a car should have like
virtual void openDoor();
virtual void enableMods();
protected:
Icar(void);
};
The reason why the canstrustor is protected is also the virtual construction mechanism, which I am gonna explain in a minute just bear it for some time.
Now we have and factory interface and a product interface with us and we are all set for accepting any orders.
Good news buddy, the toyota company has just called you and want you to produce cars. Now comes the time that we were waiting from so long. Now we have all the basic interfaces in place first thing we will do is we will create a concrete car factory.
class CarFactory :
public ICarFactory
{
private:
CarFactory(void);
//Methods that may vary for different cars
void CreateFrame(){/* Some imlementation*/};
void CreateTyre(){/* Some imlementation*/};
void CreateSeat(){/* Some imlementation*/};
static ICarFactory *instance;
public:
virtual ~CarFactory(void);
static ICarFactory* GetCarFactory()
{
if(0 == instance)
{
instance = new CarFactory;
}
return instance;
}
Icar* CreateCar(){/*Wait we will do something here to create the car*/};
};
//static member variables definition
ICarFactory * CarFactory::instance = 0;
Now carefully observe this factory we have just created. What we have done is that we have implemented all the methods from the ICarafctory interface that are required to create a car. We have implemented a method which will actually create a car, i.e. CreateCar(). And the function GetCarFactory() to return the car factory
The member variable instance is to make the class a singleton. Well we are creating a factory to create the cars bit does it really make sense to have a lot of factories floating around in the application. Probably not, so I thought of making it singleton.
Now let me explain a little bit about the function GetCarFactory and CreateCar, since they are also defined in the interface and returning ICarFactory* and ICar* respectively. Well this is what is called as virtual construction.
See what we are doing is we are making an interface and making its constructor protected. Now this class can only be inherited. We also define a method called GetCarFactory returning ICarFactory* and made it static.
Now The CarFactory is implementing this interface so it implemented this function. Now inside this class we will make the constructor private, so the only way to create a factory will be using this function only. Now in this function we will create a type CarFactory and return its pointer.
The benefit from this that, if we have multiple factories, the application need not keep a track of these factories remember ‘but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.’.
The application now will just keep ICarFactory with it and create the concrete factories like
ICarFactory* factory = CarFactory::GetCarFactory();
Now here the application has pointer to the ICarFactory and it is leting the subclass cretae its obbject. Virtual construction isn’t it.
Same is that case with ICar interface. The ICar has a Create function returning ICar*. So lets just write our toyoya which implements this function.
class toyota : public Icar
{
public:
~toyota(void){};
static car* Create()
{
return new toyota();
}
//Some functions that a car should have like
virtual void openDoor(){/*Some implenmentation*/};
virtual void enableMods(){/*Some implenmentation*/};
private:
toyota(void){};
};
Now if we want to create a car we just can use ICar* to create the car. In our case the CarFactory wants to create this car so lets just put this car creation in place.
class CarFactory :
public ICarFactory
{
private:
CarFactory(void);
//Methods that may vary for different cars
void CreateFrame(){/* Some imlementation*/};
void CreateTyre(){/* Some imlementation*/};
void CreateSeat(){/* Some imlementation*/};
static ICarFactory *instance;
public:
virtual ~CarFactory(void);
static ICarFactory* GetCarFactory()
{
if(0 == instance)
{
instance = new CarFactory;
}
return instance;
}
Icar* CreateCar()
{
car *c = toyota::Create();
return c;
};
};
//static member variable definition
ICarFactory * CarFactory::instance = 0;
Here we can see in create car function we have again utilized the virtual construction mechanism and used Icar* to create the Toyota.
Now we have all the code in place. Don’t you believe me. Well look at the code and we are all done. Now what our sales department needs to do is the question. I mean what should be done to use the factory and produce a car.
ICarFactory* factory = CarFactory::GetCarFactory();
car *myCar = factory->CreateCar();
that’s it and myCar contains a toyota.
Now let us try to visualize the factory pattern and map our implementation with it.
Our ICarFactory corresponds to Creator, Product Corrspond to ICar, Toyota corresponds to ConcreteProduct and CarFactory is ConcreteCreator. Now it looks like we have successfully implemented the factory pattern.
Now we know know how to implement the factory pattern lets just try to find its applicability.
Use the Factory Method pattern when
• a class can't anticipate the class of objects it must create.
• a class wants its subclasses to specify the objects it creates.
• classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
Well this is the basic implementation of the factory pattern. We will discuss the various versions of this pattern and there pros and cons some other time, but to understand the factory pattern I have followed a reverse approach. i.e. first code then understand and it worked for me. I hope this article will be a little useful for understanding the factory pattern in a C++ way.
No comments:
Post a Comment