Introduction
In today’s article, we will look at the Proxy pattern. We will look at what this pattern is, the advantages of using this pattern, when it should and should not be used, and finally, we will look at a sample implementation of this pattern in a C# application.
The Proxy Pattern
The Proxy pattern is used to provide an interface that is customized for the consumer. In many cases we do not want to expose all properties and methods to the final consumer. Hence, in this case, we cannot expose the main class itself. In these cases, we can create an intermediate class or proxy class which will only expose the properties and methods that are required by the final consumer. It might not be required where we need to expose all properties and methods of the final class.
A simple implementation of the Proxy Pattern
We will now look at a simple implementation of the proxy class. This application has been created using the Visual Studio 2019 Community Edition, which is a free version.
We create a new console application in .NET Core 3.1, as below.
The final solution looks like this,
The complete code is as below.
// Program.cs
using System;
namespace ConsoleAppProxyPattern {
class Program {
static void Main(string[] args) {
// Create proxy
var employeeInfoproxy = new EmployeeInfoProxy();
Console.WriteLine("The Salary is " + employeeInfoproxy.getSalaryDetails(100));
Console.ReadKey();
}
}
}
// IEmployeeInfo.cs
namespace ConsoleAppProxyPattern {
public interface IEmployeeInfo {
double getSalary(int employeeId);
double getTax(int employeeId);
}
}
// EmployeeInfo.cs
namespace ConsoleAppProxyPattern {
public class EmployeeInfo : IEmployeeInfo {
public double getSalary(int employeeId) {
// Make a call to a storage (e.g. DB) and get the salary amount
return 2000.00;
}
public double getTax(int employeeId) {
// Make a call to a storage (e.g. DB) and get the salary amount
var salary = 2000.00;
var tax = salary * 0.05;
return tax;
}
}
}
// EmployeeInfoProxy.cs
namespace ConsoleAppProxyPattern {
public class EmployeeInfoProxy {
private EmployeeInfo empInfo = new EmployeeInfo();
public double getSalaryDetails(int employeeId) {
return empInfo.getSalary(employeeId);
}
}
}
In the above code, we see that we have created a proxy class for the employee info class and then we only expose the get salary details method and not the get tax method. We could also do some further data cleaning etc. in the proxy class. Hence, when the final consumer only needs the salary details and we do not want to expose the tax details, we can use this proxy class to give access to that final consumer. We do not need to provide access to the main employee info class.
When we run the application, we get the below.
Summary
In this article, we looked at the proxy pattern and what are the advantages of using this pattern. The example given here is a simple one, but the main idea was to give an outline of how this pattern is to be implemented. Happy Coding!