Design Pattern – Repository Design Pattern

As I see it the repository pattern have two purposes; first it is an abstraction of the data layer and second it is a way of centralising the handling of the domain objects.

Data Access Objects

I still think this is one of the more common ways to work with the data layer. I personal have countless time created DAOs looking like this:

public interface ArticleDao {

List<Article> readAll();

List<Article> readLatest();

List<Article> readByTags(Tag... tags);

Article readById(long id);

Article create(Article article);

Article update(Article article);

Article delete(Article article);

}

Abstraction

The idea with this pattern is to have a generic abstract way for the app to work with the data layer without being bother with if the implementation is towards a local database or towards an online API.

The methods are based on the CRUD methods; Create, Read, Update and Delete.

So my first try looked something like this:

public interface Repository<T> {    List<T> readAll();

T read(Criteria criteria); T create(T entity); T update(T entity); T delete(T entity);}

Compromise

I chose to compromise and go half way between the repository and my old DAOs. I have my interface with all the CRUD methods. I also add one more method readById(K id). This interface will cover most of my basic use cases.

public interface Repository<T, K> {    List<T> read();

T readById(K id); T create(T entity); T update(T entity); T delete(T entity);}

Criteria

We still need a way to get specific selection out of the repository. This is where I compromise.

Say we have a model called Article and we have the need of getting the latest once and the once tagged with certain tags. Let’s add another layer of interface containing these methods.

public interface ArticleRepository extends Repository<Article, Long> {
List<Article> read(); Article readById(Long id); Article create(Article article); Article update(Article article); Article delete(Article article); List<Article> readLatest(); List<Article> readByTags(Tag...tags);
}