Sobes.tech
Junior — Middle

What are the differences between Repository and Facade patterns in terms of their purpose and implementation?

sobes.tech AI

Answer from AI

The Repository and Facade patterns serve different purposes and differ in their intent and implementation:

  • Repository

    • Purpose: abstracts access to data, providing an interface for working with a collection of objects (e.g., from a database).
    • Implementation: encapsulates logic for fetching, adding, updating, and deleting data, hiding storage details.
    • Example: IRepository<T> with methods like Add, Remove, Find, etc.
  • Facade

    • Purpose: simplifies interaction with a complex subsystem by providing a simple interface.
    • Implementation: combines calls to multiple classes/subsystems into a single method or class, hiding complexity.
    • Example: a class that calls methods of several services to perform a single business operation.

In summary: Repository focuses on data management and storage, while Facade simplifies interaction with a set of complex components.

Sample code in C#:

// Repository
public interface IRepository<T> {
    void Add(T item);
    void Remove(T item);
    T FindById(int id);
}

// Facade
public class OrderFacade {
    private InventoryService inventory;
    private PaymentService payment;
    private ShippingService shipping;

    public OrderFacade() {
        inventory = new InventoryService();
        payment = new PaymentService();
        shipping = new ShippingService();
    }

    public void PlaceOrder(Order order) {
        inventory.Reserve(order);
        payment.Charge(order);
        shipping.Schedule(order);
    }
}

Thus, patterns serve different purposes and are often used together to build a clean architecture.

What are the differences between Repository and… - sobes.tech