- Structural pattern
- The intent of this pattern is to provide a surrogate or placeholder for another object to control access to it.
- If you intent to control access to the other object due to performance/security reason or other reason , then proxy pattern is the best choice.
- Best example – when you add service reference — it generates proxy to interact with an API.
- Proxy is responsible to control the actual remote API.
- Why not directly call the actual API ?? Proxy can take the responsibility of executing the code before or after calling the API.
- Proxy :- provides and interface identical to subject. It maintains a reference of the real subject.
- Subject:- Defines the common interface between the real subject and the proxy.
- Real Subject:- Defines the real object that proxy represents.
- You can have more than one proxies. You can chain it.
- This pattern adds a layer between client and actual object.
- It allows addition of new proxies without chaning the client code:- OC principle is maintained.
namespace proxydesignpattern
{
interface IService
{
void SignIn(int age);
}
public class ActualService : IService
{
public void SignIn(int age)
{
Console.WriteLine($"You have signed in. Your age is {age}");
}
}
class ProxyService : IService
{
private readonly IService _service;
public ProxyService(IService service)
{
_service = service;
}
public void SignIn(int age)
{
if(age < 18)
{
Console.WriteLine("You are too young!!");
}
else
{
_service.SignIn(age);
}
}
}
}
PROGRAM.CS
// See https://aka.ms/new-console-template for more information
using proxydesignpattern;
IService serviceObj = new ActualService();
IService proxy = new ProxyService(serviceObj);
proxy.SignIn(12);
proxy.SignIn(21);
OUTPUT
You are too young
You have signed in. Your age is 21.
GITHUB