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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: