Repositories and Factories
Today I conclude my series on Domain Driven Design. In the first
part we looked at a brief introduction and the concept and
Entities. In the second part we covered Value Objects and Services.
Today we'll look at Repositories and
Factories.
Eventually, when defining your Domain language, you are going to
have to interact with the data stores and/or back end systems. This
is where Repositories come into the picture. A
Repository is meant to translate the data from the
user identifiable Domain Language into the format needed for the
data store, and then to perform the operations needed to send it
there.
I will create an interface for each Entity that needs to be
stored using a repositories. So, we have a Reservation Entity, I'll
have an interface called the IReservationRepository. It
will define all of the CRUD operations. Then, for each datastore,
I'll create a repository class that implements one or more of these
interfaces. We may have the SqlServerRepository that
implements IReservationRepository,
ILocationRepository, etc. The piece that ties this
together is the Factory.
I'll create a factory called the RepositoryFactory that
has a method called GetReservationRepository that returns
an IReservationRepository. It looks in a configuration
file to get the correct class (the SqlServerRepository) that needs
to be created and returned to be used as the
IReservationRepository.
So, what does all of this buy us? Let's say that today you are
storing your reservations in a database, but tomorrow you need to
store them in some other type of back end system. You create a new
repository implementing the interface and modify your configuration
file and you are up and running with the new data store. Or, if you
want to write unit tests using a mock repository that doesn't hit
an actual database that is easy to do as well.
Conclusion
So, this has been a brief overview of Domain Driven Design. I
have found this to be a very useful tool when designing systems as
it fits in cleanly with the rest of our user-centric methodology
and gives you a concise framework that can be used to architect
anything from the most simple application to the very complex.
There are two books that I would recommend for those that want
to dig deeper into the subject. Those books are:
<!--[if !supportLists]-->·
Domain-Driven Design: Tackling Complexity in the Heart of
Software by Eric Evans<!--[endif]-->
<!--[if !supportLists]-->·
Applying Domain-Driven Design and Patterns: With Examples in C# and
.NET by Jimmy Nilsson<!--[endif]-->