visit
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;
}
}
In the OrderFacade
class, we create instances of the subsystems and offer a simple method PlaceOrder
that takes in the product id, quantity, amount, and shipping address. The PlaceOrder
technique uses the subsystems to check the inventory, charge the customer, and ship the product.
With the facade pattern, the client code can create an instance of the OrderFacade
class and call the PlaceOrder
method without worrying about the details of the subsystems.
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");
}
Also published