Proxy Design Pattern in C#


Proxy design pattern is the example of Structural pattern. This design pattern is used to provide a proxy object which reference to other class object.

In proxy design pattern, there will be proxy class which represent the functionality of real class.

Now let’s see very basic example of proxy design pattern:

using System;

namespace ProxyDesign_Pattern_Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            ProxyClient obj = new ProxyClient();
            Console.WriteLine("Data from proxy={0}",obj.getData());
            Console.Read();
        }
    }

    public interface IClient
    {
        string getData();
    }

    public class RealClient : IClient
    {
        string msg;
        public RealClient()
        {
            Console.WriteLine("Real Client initialized ");
            msg = "My Test data";
        }
        public string getData()
        {
            return msg;
        }
    }

    public class ProxyClient : IClient
    {
        RealClient client = new RealClient();
        public ProxyClient()
        {
            Console.WriteLine("Proxy Client initialized");
        }
        public string getData() 
        {
          return  client.getData();
        }
    }
}

Explanation:

In the above example, we saw that we have created proxy class i.e ProxyClient and we are calling the original class method in proxy class. So this design pattern is called proxy design pattern.

Proxy_Design_Pattern

Advertisements

Factory pattern in C#


Note: If you are new to design pattern please look the part 1 of Design Pattern

https://chandradev819.wordpress.com/2015/12/17/what-is-the-design-pattern/

Factory pattern is creational design pattern in C#. As Factory name suggest that there should be something new create and construct.

In software architecture world factory pattern means centralize creation of object.

Now let take a scenario, we are working on some application and we got the scenario to generate the invoice on basis of City wise. Then generally we will write the two methods for generating the invoice and we will create the object with new keyword in UI layer.

Now we can optimize this code using factory design pattern. If we are using factory design pattern then no need create object in UI layer using New keyword. We can create factory class which will handle this task.

Now i am going to show extremely basic demo sample code for factory design pattern.

using System;

namespace factorypattern_example
{

    public class Program
    {
        public static void Main(string[] args)
        {
            Iinvoice objInvoice;
            Console.WriteLine("Enter the area Code");
            int invoiceType = Convert.ToInt32(Console.ReadLine());
            objInvoice = FactoryInvoive.GetInvoice(invoiceType);
            objInvoice.print();
            Console.ReadLine();
        }

    }

    /// <summary>
    /// Here we have created interface for common functionality
    /// </summary>
    public interface Iinvoice
    {
        void print();
    }

    /// <summary>
    /// Here we have implemented interface for bangalore branch
    /// </summary>
    public class ProductBangalore : Iinvoice
    {
        public void print()
        {
            //Note: this the demo code 
            Console.WriteLine("Invoice will be printed for Bangalore product");
        }
    }

    /// <summary>
    /// Here we have implemented interface for Mumbai branch 
    /// </summary>
    public class ProductMumbai : Iinvoice
    {
        public void print()
        {
            Console.WriteLine("Invoice will be printed for Mumbai product");
        }
    }

    /// <summary>
    /// Here we are creating the factory, which will take care of object creation task.
    /// </summary>
    public class FactoryInvoive
    {
        static public Iinvoice GetInvoice(int CityCode)
        {
            Iinvoice objInv;
            if(CityCode==100)
            {
                objInv = new ProductBangalore();

            }
           else if(CityCode==101)
            {
                objInv = new ProductMumbai();
            }
            else
            {
                return null;
            }
            return objInv;
        }
    }
}

Summary

If you observed in above code, in main method we are not creating object of class and factoryInvoice class has been created to handle the object creation task so this pattern is called as Factory Design Pattern.

What is the design pattern?


The design patterns are the recurring solution to recurring problem in Software architecture.
OR
Design pattern are the time tested practices for OOP problem. It is the process of solving object oriented programming language in much better ways.

There are 3 basic classification o design pattern

1. Creational patterns
2. Structural Patterns
3. Behavioral Pattern

Now let see some example of Creational Patterns example

1. Singleton Pattern
2. Abstract Factory Pattern
3. Factory Method pattern
4. Prototype Pattern
5. Builder Pattern

Singleton Pattern:

In this design pattern, we can create only one instance of Class. That instance needs to be accessible in different part of application. It can be use as global.
For example, we can use this pattern in so many scenarios like logging, Database access, and Holding Database Connection instance etc.

This pattern can be achieved by

1. Creating private construct of class.
2. Creating Instances and Method as static.

Now create the class like given below

namespace WebApplication2
{
    public class SingleTonTest
    {
        public static int intCounter;
 
        private SingleTonTest()
        {
        }
 
        public static void Hit()
        {
            intCounter++;
        }
 
        public static int getTotalHits()
        {
            return intCounter;
        }
    }
}

Step 2 Write the code in UI Layer like this

using System;
 
namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
 
        protected void Button1_Click(object sender, EventArgs e)
        {
            HiCounter();
        }
 
        private void HiCounter()
        {
            SingleTonTest.Hit();
            Label1.Text = SingleTonTest.getTotalHits().ToString();
        }
 
        protected void Button2_Click(object sender, EventArgs e)
        {
            HiCounter();
        }
    }
}

Summary:

Here we learnt that how to use singleton design pattern in C#.