Implementation of Abstract Factory Pattern with ADO.NET

Implementation of Abstract Factory Pattern

Introduction

This blog will discuss the  Implementation of  Abstract Factory Design Pattern. Using this example you can connect any type of database provider without any changes in code.

About Abstract Factory

Abstract factory pattern is useful when client need to create “Which are somehow related”. If we need to create a family of related or dependent object then the use of abstract factory pattern

Step 1 Database Setup 

Create table name EMPLOYEE with column name EMP_ID and EMP_NAME. We will create a service to input the user id and get the name of the employee.  

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

SET ANSI_PADDING ON

GO

CREATE TABLE [DBO].[EMPLOYEE](

 [EMP_ID] [INT] NULL,

 [EMP_NAME] [VARCHAR](50) NULL

) ON [PRIMARY]

GO

SET ANSI_PADDING OFF

GO

INSERT INTO EMPLOYEE(EMP_ID,EMP_NAME)

VALUES(1,'AMIT')

INSERT INTO EMPLOYEE(EMP_ID,EMP_NAME)

VALUES(2,'SONU')

INSERT INTO EMPLOYEE(EMP_ID,EMP_NAME)

VALUES(3,'RAM')

 

Step 2: Create a Console Application

using System;

using System.Data.Common;

//Impelentation of Abstract factory patteren

public class ashish

{   
public
static DbConnection CreateConnection(string provider, string connection)

    {

        DbConnection con = null;

        if (con == null)

        {

           
try

            {

                DbProviderFactory dp = DbProviderFactories.GetFactory(provider);

                con = dp.CreateConnection();

                con.ConnectionString = connection;

            }

            catch (Exception e1)

            {

                Console.WriteLine(e1.Message);

            }

        }

        return con;

    }

}
 
class
tarun

    static void Main(string[] args)

    {
        DbConnection con = ashish.CreateConnection("System.Data.SqlClient", "initial catalog=wcf;data source=AMIT-PC\\MIND;Integrated
Security=False;uid=sa;pwd=Mind1234"
);

        con.Open();

        DbCommand cmd = con.CreateCommand();

        cmd.CommandText = "select * from EMPLOYEE";

        DbDataReader rd = cmd.ExecuteReader();

        Console.WriteLine("Abstract Factory Pattern....");

        while (rd.Read())

        {

            Console.WriteLine(rd["EMP_ID"] + " " + rd["EMP_NAME"]);

        }

        Console.ReadKey(true);
    }

}

Image1.jpg

Next Recommended Reading Factory Design Pattern In C#