Proxy Design Pattern – Object Oriented Design – C Sharp

We will look at c sharp code of the Proxy design pattern in object oriented design creates objects that control the creation of and access to other objects. The proxy is often a small (public) object that stands in for a more complex (private) object that is activated once certain circumstances are clear.

proxy-design-pattern-uml-diagram

proxy-design-pattern-uml-diagram

Proxy Pattern

Interface ISubject

Class Proxy Implements ISubject

Class Subject Implements ISubject

Class Client

Member Variables Member Variables Member Variables Member Variables
ISbuject Subject ISubject Proxy
Member Functions Member Functions Member Functions Member Functions
Request Request Request

 

Use it when
You have
  1. Objects which are expensive to create
  2. Which need access control
  3. Which access remote sites
  4. Need to perform some action whenever they are accessed
You want
  1. Create object when some operation is called on it
  2. Want to put access control when accessed
  3. Have local object which will access remote object

 

CSharp Code for Proxy Design Pattern

class MainApp
{
static void Main()
{
var proxy = new MathProxy();
Console.WriteLine(“4 + 2 = ” + proxy.Add(4, 2));
Console.ReadKey();
}
}
public interface IMath
{
double Add(double x, double y);
}
class Math : IMath
{
public double Add(double x, double y) { return x + y; }
}
class MathProxy : IMath
{
private IMath math;
public MathProxy()
{
math = new Math();
}

public double Add(double x, double y)
{
return math.Add(x, y);
}
}

Leave a Reply

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