Wednesday, October 26, 2016

Proxy Pattern

Proxy pattern provides placeholder for another object to access it. It provides wrapper and delegation to protect actual object and its complexity from end user. Proxy pattern falls under structural pattern of GOF (Gang of Four) pattern.

When to use –

Proxy pattern can be used when you want to access remote object using local object. The remote object can be from network, file, service or any other object. Proxy acts as wrapper for simplifying complex objects and provides simpler way to access it. Proxy can also be used to provide additional functionality over actual object without changing real object’s code like adding thread safety to actual object.

Below are types of proxy.
  • Virtual Proxy – This type of proxy can be used to create objects that are heavy and complex. So using virtual proxy you can create them on demand.
  • Remote Proxy – This type of proxy provides local interface for an object that is in remote location (in different address space). The example of remote proxy is the use of WCF/Web service where client accessing remote code located on different server on different network.
  • Protection Proxy – This type of proxy can be used when you want add authentication mechanism for client to access real object.
  • Smart Proxy – This type of proxy can be used to add additional functionality to manage resources efficiently. For example, counting number of references to real object, making real object thread safe etc.

Major components of Proxy pattern –

Subject – This is an interface provides abstract methods to access using proxy class.
Real Subject – This is concrete class which implements subject interface.
Proxy – This is proxy class and used by client to access real object. Proxy class has reference to actual object and resources.

See below example of proxy pattern.

Code –
public interface IPayment
    void PayAmount(double amount);
//real subject
public class CashPayment : IPayment
    public void PayAmount(double amount)
        Console.WriteLine("The amount of Rs. {0} paid in cash", amount);
//proxy class
public class CardPayment : IPayment
    CashPayment cashPay;
    public void PayAmount(double amount)
        if (cashPay == null)
            cashPay = new CashPayment();

class Program
    static void Main(string[] args)
        IPayment payment = new CardPayment();

Output –

As you can see in above example, CardPayment class acts as proxy class. CardPayment class has referent to real object which is CashPayment. So whenever you pay amount using CardPayment proxy class which actually pay amount from real object which is CashPayment. So CardPayment class acts as intermediate/wrapper between CashPayment and Client.

I hope this article helps you to know more about Proxy Pattern. Please leave your feedback in comments section below.

References –

See Also –