A Factory encapsulates the complex logic of creating domain objects, especially when creation involves multiple steps or validation.
When to use:
Complex object creation logic
Multiple ways to create the same object
Creation involves external dependencies
Need to enforce creation invariants
public class OrderFactory
{
public Order CreateOrder(Customer customer, List<OrderItemRequest> items)
{
ValidateCustomer(customer);
ValidateItems(items);
var order = new Order(customer.Id);
foreach (var item in items)
{
var product = _productRepository.GetById(item.ProductId);
order.AddItem(product, item.Quantity);
}
return order;
}
private void ValidateCustomer(Customer customer)
{
if (!customer.IsActive)
throw new InvalidOperationException("Inactive customer");
}
}
Rewriting in plainer words…
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.