Structural Patterns, Proxy Design Pattern in C#, Example Of Proxy Pattern in C#

Proxy Design Pattern is one of the Structural Patterns. Proxy pattern in C# is basically used to control the creation and access to other objects. That means in proxy pattern we create object that decides the when to create object of particular class and controls the access of that object.

 

In Proxy design pattern, proxy is virtual placeholder for expensive objects. This proxy will decide when to create that expensive object. Proxy pattern is also useful when you need to create object for remote class.

 

Here we discuss about proxy pattern in C# with small bank example.

Suppose we have a Banker class which implements the Ibank interface as shown below.

 

public interface IBank

{

            string Pay();

}


private class BankClass : IBank

{

            public string Pay()

            {

                return "Payment From Bank";

            }

}

 

BankClass implements the Ibank interface Pay() method. If you provide the direct access of this BankerClass to client, client may create unnecessary objects. Instead of that we provide the access to BankClass through proxy class BankClassProxy as shown below.

 

public class BankClassProxy : IBank

{

            BankClass bank;

            public string Pay()

            {

                string returnMsg;

                if (bank == null)

                {

                    returnMsg = "Proxy object is not created for BankClass class";

                    bank = new BankClass();

                    return returnMsg;

                }

                else

                {

                    returnMsg = bank.Pay();

                    return returnMsg;

                }

            }

}

 

Here BankClass is private and BankClassProxy is public. So client has to create object for BankClasssProxy class only to access BankClass class. BankClassProxy also implements the Ibank interface. In Pay() method of BankClassProxy, we check whether object of BankClass is available. If it is available, we returns that object otherwise we create object for BankClass.

                                                                                                      CSharpProxyPattern.zip (23.51 kb)