The Repository pattern encapsulates the logic for accessing a data source (e.g., DB, API, etc.), providing an abstraction layer between the domain logic and the data storage mechanism. The main goal is to hide the implementation details of storage and provide a way to work with a collection of domain objects.
Advantages:
Example code in C#:
public interface IUserRepository { User GetById(int id); void Add(User user); } public class UserRepository : IUserRepository { private readonly DbContext _context; public UserRepository(DbContext context) { _context = context; } public User GetById(int id) => _context.Users.Find(id); public void Add(User user) => _context.Users.Add(user); }
Key features:
Does the Repository have to know about the database structure?
No. The Repository should operate on domain objects and hide storage details. A separate Data Access Layer is responsible for mapping to the DB schema.
Can business logic be mixed within the repository class?
No. This violates Separation of Concerns: the Repository is only responsible for fetching/saving data. Business logic should be pushed into services/domain objects.
Are Repository and DAO the same?
Not quite. DAO is orthogonal to the Repository pattern, working at the level of tables and records, while Repository deals with business logic objects. Repository abstracts collections of business entities, whereas DAO is closer to infrastructure.