Home  >  Article  >  Backend Development  >  What is the proxy design pattern and how to implement it in C#?

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

WBOY
WBOYforward
2023-09-05 12:21:101278browse

什么是代理设计模式以及如何在 C# 中实现它?

The proxy pattern provides a proxy or placeholder object to control access to a different object.

Proxy objects are used in the same way as their containing objects

Participants

Subject defines a public interface for RealSubject and Proxy so that Proxy can be used wherever RealSubject needs it use.

RealSubject defines the specific object represented by Proxy.

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

possibly. If you've ever needed to change the behavior of an existing object without actually changing that object's definition, the proxy pattern allows you to do just that. Additionally, this is useful in test scenarios where you may need to replicate the behavior of a class 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;
   }
}

The above is the detailed content of What is the proxy design pattern and how to implement it in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete