Factory Method Design Pattern
What is Factory Pattern?
Factory pattern is one of the most commonly used design pattern. It comes under creational design pattern as we have control on object creation logic. In this approach we have control over object creation instead of client application using common interface.
Depending on the situation we will return different objects and each and every time to get new object we have to request Factory class to return that object.
Example of Factory Pattern
Common Interface
public interface Figure
{
void displayFigureName();
}
Different classes implementing Interface
public class Triangle : Figure
{
public void displayFigureName()
{
Console.WriteLine("Type 1 and Default Type- Triangle");
Console.ReadKey();
}
}
public class Rectangle : Figure
{
public void displayFigureName()
{
Console.WriteLine("Type 2 - Rectangle");
Console.ReadKey();
}
}
public class Circle : Figure
{
public void displayFigureName()
{
Console.WriteLine("Type 3 - Circle");
Console.ReadKey();
}
}
Factory Class
public class FigureFactory
{
public Figure getFigure(int figureType)
{
switch(figureType)
{
case 1: return new Triangle();
case 2: return new Rectangle();
case 3: return new Circle();
default: return new Triangle();
}
}
}
Main Class
class Program
{
static void Main(string[] args)
{
FigureFactory figureFactory = new FigureFactory();
Figure figure1 = figureFactory.getFigure(1);
figure1.displayFigureName();
figure1 = figureFactory.getFigure(2);
figure1.displayFigureName();
figure1 = figureFactory.getFigure(3);
figure1.displayFigureName();
figure1 = figureFactory.getFigure(4);
figure1.displayFigureName();
}
}
Explanation
Here, We have an interface called Figure which is implemented by three classes Triangle,Rectangle and Circle. Our Factory class contains getFigure() method which returns object of any of
Triangle,Rectangle or circle depending on figureType. When we are passing 1 to getFigure() it will give object of Triangle() and figure1.displayFigureName() will make a call to method of Triangle,
when passing 2 it will give object of Rectangle, for passing 3 it will give object of Circle, For other values it will follow default case and return object of Triangle class. Depending on object returned displayFigureName() will make call to method defined in corresponding class.
Factory class is our object creation logic we may use some other logic for object creation.
Advantages
1) It provides abstraction of object creation as object creation logic is hidden from outside world.
2) Used to design flexible system which are highly adaptable.
1 Comment(s)