代理模式
1. 基于开闭原则 OCP: 对扩展开放,对修改封闭。
购物类:
namespace ProxyPattern { public interface IShopping { void ChoiceProduct(string product); void PayForProduct(); public string GetCurrentProducts(); } public class Shopping : IShopping { private readonly List<string> _productList = new List<string>(); public void ChoiceProduct(string product) { if (!string.IsNullOrEmpty(product)) { _productList.Add(product); Console.WriteLine($"You has choiced {product}"); } } public void PayForProduct() { foreach (var product in _productList) { Console.WriteLine($"You has bought {product}"); } } public string GetCurrentProducts() { string allProducts = ""; foreach (string item in _productList) { allProducts += item + " "; } return allProducts; } } }
代理类:
public class ProxyShopping { private readonly IShopping _shopping = new Shopping(); public void ChoiceProduct(string product) { _shopping.ChoiceProduct(product); Console.WriteLine($"Add [choice {product}] Debug Log."); } public void PayForProduct() { _shopping.PayForProduct(); Console.WriteLine($@"Add [pay for {_shopping.GetCurrentProducts()}] Debug Log."); } }
代码调用:
class Program { static void Main(string[] args) { ProxyShopping proxyShopping = new ProxyShopping(); proxyShopping.ChoiceProduct("Clothes"); proxyShopping.ChoiceProduct("PC"); proxyShopping.PayForProduct(); } }