-> In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.
-> Separate object creation from the decision of which object to create.
-> Defer creation of objects. Only create them if and when needed.
-> Creating instance of several of derived classes. Factory method decides which derived concrete object to be created.
Step 1
-> Create an interface
Shape.cs
1 2 3 4 |
public interface Shape { void draw(); } |
Step 2-> Create concrete classes implementing the same interface.
Rectangle.cs
1 2 3 4 5 6 7 |
public class Rectangle : Shape { public void draw() { Console.WriteLine("Inside Rectangle : Draw method."); } } |
Square.cs
1 2 3 4 5 6 7 |
public class Square : Shape { public void draw() { Console.WriteLine("Inside Square : Draw method."); } } |
Circle.cs
1 2 3 4 5 6 7 |
public class Circle : Shape { public void draw() { Console.WriteLine("Inside Circle : Draw method."); } } |
Step 3
Create a Factory to generate object of concrete class based on given information.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public class ShapeFactory { //use getShape method to get object of type shape public Shape getShape(String shapeType) { if (shapeType == null) { return null; } if (shapeType.Equals("CIRCLE")) { return new Circle(); } else if (shapeType.Equals("RECTANGLE")) { return new Rectangle(); } else if (shapeType.Equals("SQUARE")) { return new Square(); } return null; } } |
Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class Program { static void Main(string[] args) { ShapeFactory shapeFactory = new ShapeFactory(); //get an object of Circle and call its draw method. Shape shape1 = shapeFactory.getShape("CIRCLE"); //call draw method of Circle shape1.draw(); //get an object of Rectangle and call its draw method. Shape shape2 = shapeFactory.getShape("RECTANGLE"); //call draw method of Rectangle shape2.draw(); //get an object of Square and call its draw method. Shape shape3 = shapeFactory.getShape("SQUARE"); //call draw method of circle shape3.draw(); Console.Read(); } } |