Facade,Pattern

Erhan 8/7/2016 0

Facade Pattern

C#
 Challenge
You are working on a database application. Frequently you need to execute UPDATE
and DELETE SQL queries. Each time there is a need to create the SqlConnection and
SqlCommand class, assign the connection to command and execute the query.
The series of activities looks like:
SqlConnection connection = new SqlConnection("connection string" );
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "UPDATE Customer SET Processed=1";
command.ExecuteNonQuery();
You need to repeat the same code wherever execute queries are required. How to
make this code better?
Definition
GoF Definition: "Provide a unified interface to a set of interfaces in a system. Facade
defines a higher-level interface that makes the subsystem easier to use"
Implementation
Using Façade, we can improve the situation. We can find only the query is different
in each case - the parameters like connection string is common for the entire
application.
SQLFacade.ExecuteSQL("UPDATE query here.." );
After using the Façade the code will look like above.
The complicated code is being pulled to the background SQLFacade class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace FacadePattern
{
    public class SQLFacade
    {
        public static bool ExecuteSQL( string sql)
        {
            SqlConnection connection = new SqlConnection( "connection string");
            SqlCommand command = new SqlCommand();
            command.Connection = connection;
            command.CommandText = sql;
            command.ExecuteNonQuery();

            return true ;
        }
    }
}

**************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace FacadePattern
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection connection = new SqlConnection( "connection string");
            SqlCommand command = new SqlCommand();
            command.Connection = connection;
            command.CommandText = "UPDATE Customer SET Processed=1" ;
            command.ExecuteNonQuery();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SQLFacade.ExecuteSQL("UPDATE query here.." );
        }
    }
}

  
 

Report Bug

Please Login to Report Bug

Reported Bugs

Comments

Please Login to Comment

Comments