Introduction
Factory pattern deals with the instantiation of object without exposing the instantiation logic. In other words, a Factory is actually a creator of objects which have common interface.
It will increase the performance of your application is rapidly increased and the cost of the application is free fall.
Example
I’m having many oracle packages, each has many stored procs. Here some of the in parameters are similar to all the packages and also to the stored procs.
In the above diagram shows that each packages has many stored proc’s and each stored proc has many entities.
Here each stored proc has its own in and out parameters but some of the parameters are same for all the stored procs. Now take the common parameters out and create base class with those common entities.
We can implement the above scenario with the below approach.
- using System;
-
-
-
-
-
- namespace FactoryMethod
- {
- Product (abstract)
-
-
-
-
- public interface ITree
- {
- string GetTreeName();
- }
- Products (concrete)
-
-
-
-
-
- public class BananaTree : ITree
- {
- public string GetTreeName()
- {
- return "My Name Is Banana Tree";
- }
- }
-
-
-
-
-
- public class CoconutTree : ITree
- {
- public string GetTreeName()
- {
- return "My Name Is Coconut Tree";
- }
- }
- Factory (abstract)
-
-
-
-
-
- public interface TreeType
- {
- ITree GetTree(string tree);
- }
- Factory (concrete)
-
-
-
-
- public class ConcreteTreeType : TreeType
- {
-
- public ITree GetTree(string tree)
- {
-
- if (tree == "COCONUT")
- return new CoconutTree();
- else
- return new BananaTree();
-
- }
- }
- Client code
-
-
-
-
- class Program
- {
- static void Main(string[] args)
- {
- TreeType oTreeType = new ConcreteTreeType();
-
- ITree banana = oTreeType.GetTree("COCONUT");
- Console.WriteLine(banana.GetTreeName());
-
- Console.ReadKey();
- }
- }}
Conclusion
In Factory pattern, we create object without exposing the creation logic. In this pattern, an interface is used for creating an object but let subclass decide which class to instantiate.