C# Proxy Design Pattern

Link To source Code for this article

This pattern is used to restrict access to Real Subject Class by creating Proxy gate, that implement the same interface as Real Subject and extends the interface methods to perform additional operations before executing method in Real Subject. Proxy Design Pattern acts as main point of contact for the resources that should not be available directly to the client code.

To demonstrate the implementation of this pattern I’ll use an example of in game equipment where access to the items is restricted by Proxy.

 

UML diagram:

l4

 

 

 

 

 

 

 

 

 

 

Let’s begin by creating Interface that will be implemented by both Classes.

~~~ c# public interface IEquipment { string GetData(); ~~~
Nothing fancy, just to demonstrate the idea behind the pattern. Subject Interface provides and interface that both actual class and proxy class will implement. this way the proxy can easily be used as substitute for the real subject.

Next step is to create Equipment Class that is our Real Subject

~~~ c# public class Equipment : IEquipment { string itemName; public int intemId; //Constructor public Equipment() { itemName = "Iron Sword"; intemId = 4; }

public string GetData() { return (itemName + " ID: "+ intemId.ToString()); } ~~~
This class also contains one item with name and ID, which is represented just by fields, in more real example it would be list of Items. We assign new values when instance of this class is created.

Now we need to create Proxy that will have a reference to the Real Subject  and will modify the GetData() method to restrict the access.

public class EquipmentProxy : IEquipment
{
  Equipment client = new Equipment();

  public string GetData()
  {
     if (client.intemId == 4)
         return client.GetData();

     else
         return "Item is not in inventory";
   }
 ~~~    
Id is hard typed and set to 4 just for the example. The application will use this class and this class will internally take care of talking to the RealSubject and get the data to the local application.

Last part of the application is Client site, where Instance of the proxy is created and GetData() method is called.

~~~ c#  class Program
{
  static void Main(string[] args)
  {
     EquipmentProxy proxy = new EquipmentProxy();
     Console.WriteLine("Data from Proxy: "+ proxy.GetData());

     Console.ReadKey();
  }

 

To conclude, The proxy design pattern is used to provide a surrogate object, which references to other object. Proxy pattern involves a class, called proxy class, which represents functionality of another class. I hope you learned something new, in next article I’ll cover another design pattern. Stay Awesome!