Now in this post I will look at one of the categories of design patterns and an example. Creational patterns define the best possible way in which an object can be instantiated. This describes the best way to create object instances. There are different types of Creational patterns and in this post we are going to look at the Factory pattern.
Factory Pattern
Factory of what? Of classes. In simple words, if we have a base class and a number of sub-classes, and based on the data provided, we have to return the object of one of the sub-classes, we use a factory pattern. Here is an example:
In this example, we use an abstract class as the base. The Ford, Toyota and BMW classes derive from the abstract class Vehicle.
abstract class Vehicle
{
abstract string Make {get;}
}
public class Ford : Vehicle
{
public override string Make
{
get
{
return "Ford";
}
}
}
public class Toyota: Vehicle
{
public override string Make
{
get
{
return "Toyota";
}
}
}
public class BMW: Vehicle
{
public override string Make
{
get
{
return "BMW";
}
}
}
static class Factory
{
public static Make Get(int id)
{
switch(id)
{
case 0:
return new Ford();
case 1:
case 2:
return new Toyota();
case 3:
default:
return new BMW();
}
}
static void Main()
{
for(int i = 0; i <=3; i++)
{
var vehicle= Factory.Get(i);
Console.WriteLine("Where id = {0}, position = {1} ", i , vehicle.Make);
}
}
Here is the Output
Where id = 0, position = FordWhere id = 1, position = Toyota
Where id = 2, position = Toyota
Where id = 3, position = BMW
The factory design pattern is found in the Factory class. The point of the Get method is to take a value and instantiate a class based on that value. It translate integers to objects with a switch statement. Because Ford, Toyota and BMW all derive from the same abstract class, the return type Make can be used. An implicit cast automatically casts the Ford, Toyota and BMW to Make references.
The Main method serves to demonstrate the Factory class in action. We use as part of the demonstration the integers 0, 1, 2 and 3. We user Get method with each of these values. Then, we show that the appropriate type of class was instantiated for each integer.
In short, the Factory patterns can be used in the following cases:
a) When a class does not know which class of objects it must create.
b) A class specifies its sub-class to specify which objects to create.
c) In programmer's language, you can use factory pattern where you have to create an object of any one sub-classes depending on the data provided.