Dot Net For All

Proxy Pattern With Practical C# Example

proxy pattern

In this article I will discuss about the proxy pattern. This post will also include the use cases where and how this pattern can be used with live C# example.

What is a Proxy Pattern

Proxy pattern is another structural pattern which is used to control  the creation and access of the objects. Proxy class is basically is an object which control the creation and access of the other object. Or in other words it is a representative class (which is simple  in functioning) which represents a more complex class which is created once the requirements are met. The client only knows about the proxy class and the main complex class stays behind the scene.

The main players in this design pattern are the proxy class as well as subject interface, subject class and the client.

Where the proxy pattern is used

There can be following four main type of proxies

  1. Virtual proxies – These class handle the creation of the object which is slower to create or not necessary in long run.
  2. Authentication proxies – These proxies handle the authentication part of the subject class if necessary.
  3. Remote proxies – Encodes the requests and send them across the network.
  4. Smart proxies – Adds to or change the request before sending them

Proxies like the decorator forward the request on to another object. The difference is that the proxy relationship is set up at the design time while the decorator can be added dynamically.

The proxy class is the wrapper of the main Subject class. The proxy class contains an instance of the Subject class. This relation between the proxy and subject class is aggregation. In this relation subject can exist even without the creation of the proxy class.

The proxy takes care of the all complexities of creating the subject class and it hides all these complexities from the client, And expose only the requires functionalities to the outer world.

In today’s world of service oriented architecture(SOA e.g WCF) and resource oriented architecture (ROA e.g Web API) the owner or provider of the services simple provides the endpoints.

The best example of the proxy class implementation is the WCF service. For accessing a WCF service which can be developed by some third party or by ourselves only we need to create a proxy class. You can see the creation of the proxy class in one of my article.

The proxy class should implemented an interface which contains the same methods which are exposed by the WCF service class. The proxy class takes care of making the connection to the service and as well as serialization and deserialization of the messages.

Let’s create an example for the proxy pattern

Suppose there is a ForexProvider class developed by some provider which handles the request sent by the client. The client need to have the proper format for sending a request. The Forex provider gives access some methods only if the request is validated.

 /// <summary>
    /// This is the main subject class which is created by some other person which we need to access 
    /// in our project
    /// </summary>
    public class ForexProvider
    {
        private bool isAutheticated;
        public string Request()
        {
            return "Request completed";
        }

        public string GetPrice(string currencyName)
        {
            return string.Format("The forex rate is {0} for {1}", 23, currencyName);
        }

        public string SetPrice(string currencyName, int value)
        {
            if (isAutheticated)
                return string.Format("The forex rate of {0} is set to {1}", currencyName, value);
            else
                return string.Format("Please autheticate yourself");
        }

        public bool Authenticate(string pwd)
        {
            if (pwd == "pwd")
            {
                isAutheticated = true;
                return true;
            }
            else
                return false;
        }
    }

    /// <summary>
    /// This is the subject interface which contains the same method which we need our client to access the 
    /// main subject class
    /// </summary>
    public interface IForexProvider
    {
        string Request();
        string GetPrice(string currencyName);
        string SetPrice(string currencyName, int value);
        bool Authenticate(string pwd);
    }

    /// <summary>
    /// This is the proxy class which creates and instance of the main suject class and takes care of
    /// the internal working of the main subject.
    /// </summary>
    public class ForexProviderProxy : IForexProvider
    {
        private ForexProvider forexProvider;

        public bool Authenticate(string pwd)
        {
            if(forexProvider == null)
                forexProvider = new ForexProvider();
            return forexProvider.Authenticate(pwd);
        }

        public string GetPrice(string currencyName)
        {
            if (forexProvider == null)
                forexProvider = new ForexProvider();
            return forexProvider.GetPrice(currencyName);
        }

        public string Request()
        {
            if(forexProvider  == null)
                forexProvider = new ForexProvider();
            return forexProvider.Request();
        }

        public string SetPrice(string currencyName, int value)
        {
            if (forexProvider == null)
                forexProvider = new ForexProvider();
            return forexProvider.SetPrice(currencyName, value);
        }
    }

  /// <summary>
    /// This is the client which does not know any thing abou the main subject and it only deals with 
    /// the proxy class
    /// </summary>
    class Client
    {
        static void Main(string[] args)
        {
            IForexProvider forex = new ForexProviderProxy();
            forex.Request();
            forex.SetPrice("Indian Rupee", 65);

            Console.Read();
        }
    }

In the above code the client is only aware of the proxy class. In the proxy class the instance of the Subject (ForexProvider) is only created on demand.

When Proxy pattern is should be used:

Conclusion:

In this article I have shown how the creation and use of proxy pattern can make the life of the developers life easy by encapsulating the complexities of the creation of the subject class.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview