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();
- }

Rajib Das GuptaPosted Aug 26, 2016, 5:41 AM
Nice one
kalu singh raoPosted Jul 27, 2016, 1:46 AM
Good one