What is proxy design pattern and how to implement it in C#?

CsharpServer Side ProgrammingProgramming

The Proxy pattern provides a surrogate or placeholder object to control access to another, different object.

The Proxy object can be used in the same manner as its containing object

The Participants

The Subject defines a common interface for the RealSubject and the Proxy such that the Proxy can be used anywhere the RealSubject is expected.

The RealSubject defines the concrete object which the Proxy represents.

The Proxy maintains a reference to the RealSubject and controls access to it. It must implement the same interface as the RealSubject so that the two can be used interchangeably

Probably. If you've ever had a need to change the behavior of an existing object without actually changing the definition of that object, the Proxy pattern can allow you to do that. Further, this being very useful in testing scenarios, where you might need to replicate a class's behavior without fully implementing it.

Example

internal class Program {
   private static void Main(string[] args) {

      NewServerProxy proxy = new NewServerProxy();
      Console.WriteLine("What would you like to order? ");
      string order = Console.ReadLine();
      proxy.TakeOrder(order);

      Console.WriteLine("Sure thing! Here's your " + proxy.DeliverOrder() + ".");
      Console.WriteLine("How would you like to pay?");
      string payment = Console.ReadLine();
      proxy.Processpayment(payment);

      Console.ReadKey();
   }
}

public interface IServerP {
   void TakeOrder(string order);
   string DeliverOrder();
   void Processpayment(string payment);
}
public class ServerP : IServerP {
   private string Order;
   public string DeliverOrder() {
      return Order;
   }

   public void Processpayment(string payment){
      Console.WriteLine("Server Processes the payment " + payment);
   }
   public void TakeOrder(string order) {
      Console.WriteLine("Server takes order " + order);
      Order = order;
   }
}
public class NewServerProxy : IServerP {
   private string Order;
   ServerP _server = new ServerP();
   public string DeliverOrder() {
      return Order;
   }
   public void Processpayment(string payment) {
      _server.Processpayment(payment);
   }
   public void TakeOrder(string order) {
      Console.WriteLine("Server takes order " + order);
      Order = order;
   }
}
raja
Published on 25-Nov-2020 16:49:51
Advertisements