Proxy Pattern

 

In proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural pattern. In proxy pattern, we create object having original object to interface its functionality to outer world. Proxy design pattern intent according to GoF is: Provide a surrogate or placeholder for another object to control access to it .

A proxy receives client requests, does some work (access control, caching, etc.) and then passes the request to a service object. The proxy object has the same interface as a service, which makes it interchangeable with a real object when passed to a client.

Here is an example of proxy pattern using c# .

 

public class Person
{
public int Id { get; set; }
public required string Name { get; set; }
}

public interface IMyRespository
{
List<Person> Get();
}

public class MyRespository : IMyRespository
{
public List<Person> Get()
{
Console.WriteLine("Real Repository Handling ...");
return new List<Person>();
}
}

public class Proxy : IMyRespository
{
private MyRespository _realRepo;

public Proxy(MyRespository realRepo)
{
_realRepo = realRepo;
}


public List<Person> Get()
{
var result = GetFromCache();

if (result is null)
{
result = _realRepo.Get();
}
return result;
}


private List<Person> GetFromCache()
{
Console.WriteLine("Proxy: Check If List In Cache and Get Data ... ");
return new List<Person>();
}
}

public class Client
{
public void ClientCode(IMyRespository repo)
{
// ...

repo.Get();

// ...
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *