Back to: Design Patterns in C# With Real-Time Examples
Proxy Design Pattern in C# with Examples
In this article, I am going to discuss the Proxy Design Pattern in C# with Examples. Please read our previous article where we discussed the Composite Design Pattern in C# with examples. The Proxy Design Pattern falls under the category of Structural Design Pattern. As part of this article, we are going to discuss the following pointers.
- What is Proxy Design Pattern?
- Understanding the different types of Proxies.
- Proxy Design Pattern Real-time Examples.
- Why do we need Proxy Design Pattern in C#
- Implementation of Proxy Design Pattern in C#.
- Understanding the class diagram of the Proxy Design Pattern.
- When to use the Proxy Design Pattern in real-time applications?
What is Proxy Design Pattern?
According to the Gang of four definitions, the Proxy Design Pattern provides a surrogate (act on behalf of other) or placeholder for another object to control the access to it. Proxy means ‘in place of‘ or ‘representing‘ or ‘on behalf of‘.
In the simplest form, we can define a proxy as a class functioning as an interface to something else. The proxy could interface to anything such as a network connection, a large object in memory, a file, or some other resources that are expensive or impossible to duplicate.
We can also say that the Proxy is the object which is being called by the client to access the real object behind the scene. That means, In Proxy Design Pattern, a class represents the functionality of another class.
Understanding Proxy Design Pattern in C# with an Example:
Please have a look at the following diagram for a better understanding of the Proxy Design Pattern in C#. As you can see in the following image, when the client wants to consume some methods of the Real Object, then he/she needs to go via the Proxy object. That means the client will call the method of the Proxy object and the proxy will be responsible to call the method of the Real Object.
Types of Proxies:
There are three types of proxies. They are as follows.
- Virtual Proxy: A virtual proxy is a placeholder for “expensive to create” objects. The real object is only created when a client first requests or accesses the object.
- Remote Proxy: A remote proxy provides local representation for an object that resides in a different address space.
- Protection Proxy: A protection proxy control access to a sensitive master object. The surrogate object checks that the caller has the access permissions required prior to forwarding the request.
Proxy Design Pattern Real-time Example:
Please have a look at the following diagram. On the right side, you can see the State bank of India, and on the left side a person called Anurag. Anurag has an account in the State Bank of India. In earlier days, let say 1960, Anurag wants to withdraw money from his account. Then what he has to do is, he has to carry his passbook and go to the bank. Then he has to fill the form and needs to stand in the queue. Once his turn comes he has to give the form and bank passbook to the bank employee and then the bank employee verify the form and his passbook and if everything fine then the bank employee gives the required money to Anurag.
Let’s assume Anurag wants to withdraw money nowadays. So, instead of going to the bank what he can do nowadays is, just walks to the nearest ATM with his debit card. Then he inserts his debit and enters the pin and the amount to withdraw. The ATM will then communicates with the bank and validate the pin and amount and if everything is fine then the ATM will give the money to Anurag. Instead of going to the bank, Anurag can withdraw Money from the ATM. So, here the bank is the Real Object and ATM is the Proxy. And I think this is the best real-time example of the Proxy Design Pattern.
Why do we need Proxy Design Pattern in C#?
Let us understand the need for the Proxy Design Pattern with the example of a Proxy Server.
A server that sits between a client application such as a web browser and a real server is called a Proxy Server. This Proxy server intercepts all the incoming requests for the real server to see if it can fulfill the requests by itself. If not then it will forward the requests to the real server.
The Proxy server has two main objectives. They are as follows:
Improve Performance:
The Proxy servers can drastically improve the performance of the application. This is because it saves the results of a request for a certain period of time. For example, let say we have two users X and Y and they want to access a particular resource through the proxy server. First, user X request a particular resource (let say a list of employees) and cache that resource for a certain amount of time. Later, user Y also requests the same resource, then the Proxy server instead of forwarding that request to the actual server (which is a time-consuming operation), can simply return the data from the cache. Since the client and the proxy server are in the same network, so it is going to be a much faster operation.
Filter Requests:
The Proxy servers can also be used to filter the incoming requests. For example, a company might use the proxy server to prevent its employees from accessing a specific set of websites such as Facebook, Twitter, etc.
Implementation of Proxy Design Pattern in C# (Protection Proxy):
Business Requirement:
Please have a look at the following diagram. As you can see in the following image, on the right side we have a shared computer that has a shared folder. On the left side, we have employees who are working on a software farm. The shared computer contains a shared folder that contains confidential information and only the employee having role Manager and CEO can access this shared folder and perform the read-write operations. On the other hand, if the employee is a developer, then it should not allow access to the shared folder. That is we need to do some kind of protection. In scenarios like this, the Protection Proxy can be handy.
What we can do here is, in between the employees and the shared computer we need to introduce the Folder Proxy. What this Folder proxy can do is, it will check if the employee’s role is Manager or CEO, then it allows the employee to access the shared folder and perform the read-write operation. On the other hand, if the employee role is Developer then it will say you don’t have permission to access this folder. That kind of protection logic we can write in the folder proxy.
Now, I hope you understood the Proxy Design Pattern. So, let implement the proxy design pattern in C# step by step.
Step1: Creating the Employee class
Create a class file with the name Employee.cs and then copy and paste the following code in it.
namespace ProxyDesignPattern { public class Employee { public string Username { get; set; } public string Password { get; set; } public string Role { get; set; } public Employee(string username, string password, string role) { Username = username; Password = password; Role = role; } } }
Step2: Creating Subject
Create an interface with the name ISharedFolder and then copy and paste the following code in it. This interface defines the common methods which are going to be implemented by the RealSubject and the Proxy class.
using System; namespace ProxyDesignPattern { public interface ISharedFolder { void PerformRWOperations(); } }
Step3: Creating Real Object
Create a class file with the name SharedFolder.cs and then copy and paste the following code in it. This class implements the subject (ISharedFolder) interface.
using System; namespace ProxyDesignPattern { public class SharedFolder : ISharedFolder { public void PerformRWOperations() { Console.WriteLine("Performing Read Write operation on the Shared Folder"); } } }
Step4: Creating the Proxy Object
Create a class file with the name SharedFolderProxy.cs and then copy and paste the following code in it. This class also implemented the Subject (ISharedFolder) interface as well as it also holds a reference to the real object.
using System; namespace ProxyDesignPattern { class SharedFolderProxy : ISharedFolder { private ISharedFolder folder; private Employee employee; public SharedFolderProxy(Employee emp) { employee = emp; } public void PerformRWOperations() { if (employee.Role.ToUpper() == "CEO" || employee.Role.ToUpper() =="MANAGER") { folder = new SharedFolder(); Console.WriteLine("Shared Folder Proxy makes call to the RealFolder 'PerformRWOperations method'"); folder.PerformRWOperations(); } else { Console.WriteLine("Shared Folder proxy says 'You don't have permission to access this folder'"); } } } }
Step5: Client code
Please modify the Main method as shown below.
using System; namespace ProxyDesignPattern { class Program { static void Main(string[] args) { Console.WriteLine("Client passing employee with Role Developer to folderproxy"); Employee emp1 = new Employee("Anurag", "Anurag123", "Developer"); SharedFolderProxy folderProxy1 = new SharedFolderProxy(emp1); folderProxy1.PerformRWOperations(); Console.WriteLine(); Console.WriteLine("Client passing employee with Role Manager to folderproxy"); Employee emp2 = new Employee("Pranaya", "Pranaya123", "Manager"); SharedFolderProxy folderProxy2 = new SharedFolderProxy(emp2); folderProxy2.PerformRWOperations(); Console.Read(); } } }
Output:
Understanding the Class Diagram Proxy Design Pattern:
In order to understand the class diagram of the proxy design pattern in C#, please have a look at the following diagram.
As shown in the above diagram, there are three participants involved in the proxy design pattern. They are as follows:
- Subject (ISharedFolder): This is an interface that defines members that are going to be implemented by the RealSubject and Proxy class so that the Proxy can be used anywhere the RealSubject is expected. In our example, it is the ISharedFolder interface.
- RealSubject (SharedFolder): This is a class that we want to use more efficiently by using the proxy class. In our example, it is the SharedFolder class.
- Proxy (SharedFolderProxy): This is a class that holds a reference to the RealSubject class and can access RealSubjecr class members as required. It must implement the same interface as the RealSubject so that the two can be used interchangeably. In our example, it is the SharedFolderProxy class.
When to use the Proxy Design Pattern in C# Real-Time Applications?
The following are some of the real-time scenarios where you can use the proxy design pattern in C# Real-time Applications.
- Adding security access to an existing object. The proxy will determine if the client can access the object of interest.
- Simplifying the API of a complex object. The proxy can provide a simple API so that the client code does not have to deal with the complexity of the object of interest.
- Providing interfaces for remote resources such as web service or REST resources.
- Coordinating expensive operations on remote resources by asking the remote resources to start the operation as soon as possible before accessing the resources.
- Adding a thread-safe feature to an existing class without changing the existing class code.
In the next article, I am going to discuss the Virtual Proxy Real-Time Example in C# with examples. Here, in this article, I try to explain the Proxy Design Pattern in C# with examples. I hope you enjoy this Proxy Design Pattern in C# with Examples article.