Defines an interface for creating an object of a class and hides the complexity of creating that object.
For example
When we visit a pizza store and order a pizza, after some background/hidden process we get pizza. What we do is just ask for a pizza and choice of toppings; we do not need to know about the complexity of creating pizza.
In the same way, by using Factory Pattern, we can hide the complexity of creating an object.
A very simple example of creating Factory Pattern in C# is as follows:
- public class FactoryArgs
- {
- public string ShapeType { get; set; }
- public string ShapeColor { get; set; }
- }
- public class ShapeFactory
- {
- public static IShape GetShape(FactoryArgs args)
- {
- if (args.ShapeType == "Rectangle")
- return new Rectangle() { FillColor = args.ShapeColor };
- else
- return new Circle() { FillColor = args.ShapeColor };
- }
- }
-
- public class Rectangle : IShape
- {
- public string FillColor
- {
- get; set;
- }
-
- public void DrawShape()
- {
- Console.WriteLine(string.Format("Creating rectangle shape and filling {0} color", FillColor));
- }
- }
- public class Circle : IShape
- {
- public string FillColor
- {
- get; set;
- }
-
- public void DrawShape()
- {
- Console.WriteLine(string.Format("Creating circle shape and filling {0} color", FillColor));
- }
- }
-
- public interface IShape
- {
- void DrawShape();
- }
In this example, we have ShapeFactory class responsible for creating object of IShape based on arguments we passed.
So, the client doesn't need to worry how the IShape object will be created, they just need to ask for what shape and color they want. Based on the client’s choice, factory will decide which object it will create.
- IShape _shape = ShapeFactory.GetShape(new FactoryArgs {ShapeType="Circle",ShapeColor = "red" });
- _shape.DrawShape();
- Console.ReadLine();
Output: Creating circle shape and filling red color.
- _shape = ShapeFactory.GetShape(new FactoryArgs { ShapeType = "Rectangle", ShapeColor = "black" });
- _shape.DrawShape();
- Console.ReadLine();
Output: Creating rectangle shape and filling black color.