Jan 01, 1970
public interface IInventorySystem { void Update(int productId, int quantity); bool IsAvailable(int productId, int quantity); } public interface IPaymentSystem { bool Charge(double amount); } public interface IShippingSystem { bool Ship(string address); }
public class InventorySystem : IInventorySystem { public void Update(int productId, int quantity) { // update inventory } public bool IsAvailable(int productId, int quantity) { // check if inventory is available return true; } } public class PaymentSystem : IPaymentSystem { public bool Charge(double amount) { // charge the customer return true; } } public class ShippingSystem : IShippingSystem { public bool Ship(string address) { // ship the product return true; } }
public class OrderFacade { private IInventorySystem _inventorySystem; private IPaymentSystem _paymentSystem; private IShippingSystem _shippingSystem; public OrderFacade() { _inventorySystem = new InventorySystem(); _paymentSystem = new PaymentSystem(); _shippingSystem = new ShippingSystem(); } public bool PlaceOrder(int productId, int quantity, double amount, string address) { bool success = true; if (_inventorySystem.IsAvailable(productId, quantity)) { _inventorySystem.Update(productId, -quantity); success = success && _paymentSystem.Charge(amount); success = success && _shippingSystem.Ship(address); } else { success = false; } return success; } }
在OrderFacade
类中,我们创建了子系统的实例并提供了一个简单的方法PlaceOrder
,它接受产品 ID、数量、金额和送货地址。 PlaceOrder
技术使用子系统来检查库存、向客户收费以及运送产品。
使用外观模式,客户端代码可以创建OrderFacade
类的实例并调用PlaceOrder
方法,而无需担心子系统的细节。
var order = new OrderFacade(); bool success; // place an order success = order.PlaceOrder(productId: 123, quantity: 1, amount: 99.99, address: "123 Main St"); if (success) { Console.WriteLine("Order placed successfully"); } else { Console.WriteLine("Unable to place order"); }
也发布