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
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.
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!