Factory Design Pattern

There are three types of Design Pattern -
  1. Creational
  2. Behavioral
  3. Structural
Factory Design pattern is Creational Design pattern type, which is responsible for how we create an object of class.Client. You don't have to worry about object creation, just pass the parameter and factory is responible for
creating an appropriate object and passing it to the Client.
  1. class FactoryPattern {  
  2.     /// <summary>  
  3.     /// Baiscally There are three types of Design pattern  
  4.     /// Creational, Behavioral and Structural  
  5.     /// Factory Pattern is type of Creational because, by Factory we identify how we create a object of a Class  
  6.     /// </summary>  
  7.     /// <param name="args"></param>  
  8.     public static void Main(string[] args) {  
  9.         IConnection Obj = DataBaseFactory.GetConnection("MySql");  
  10.         Obj.CreateConnection();  
  11.         Console.ReadKey();  
  12.     }  
  13. }  
  14. public class DataBaseFactory {  
  15.     public static IConnection GetConnection(string type) {  
  16.         IConnection con = null;  
  17.         switch (type) {  
  18.             case "Sql":  
  19.                 con = new SqlClass();  
  20.                 break;  
  21.             case "MySql":  
  22.                 con = new MySqlClass();  
  23.                 break;  
  24.         }  
  25.         return con;  
  26.     }  
  27. }  
  28. public interface IConnection {  
  29.     void CreateConnection();  
  30. }  
  31. public class SqlClass: IConnection {  
  32.     public void CreateConnection() {  
  33.         // ToDo:  
  34.         Console.WriteLine("Sql Connection Created");  
  35.     }  
  36. }  
  37. public class MySqlClass: IConnection {  
  38.     public void CreateConnection() {  
  39.         //ToDo:  
  40.         Console.WriteLine("MYSql Connection Created");  
  41.     }  
  42. }  
Class FactoryPattern is our client class who wants to connect to a database by providing only parameter, like MySQL or SQL.

DataBaseFactory is responsible for creating an object and sending it to the calling client.
Ebook Download
View all
Learn
View all