difference between a repository and factory pattern

Viewed 24656

Can you please outline the differences between the Repository pattern and the Factory pattern?

3 Answers

The repository pattern deals with creating a set of data access services, ie. CRUD methods. The factory pattern on the other hand deals with how an object is created. A factory class will have a method that returns a new instance of a class.

The two are independent of each other; however, you will often see the factory pattern used alongside the repository pattern in order to create a new instance of an entity.

I think the difference is the usage of both.

If you want to create objects and fill those objects with database data you will use a Repository. You can have a CustomerRepository with all related methods in it for retrieving and manipulation of Customers.

If you want to create Objects and fill those objects with data you use a Factory. An example could be a ColorFactory. You can fill that one with a lot of possible RGB colors that you will use later on.

If you look at something like "saving" data you could also use different words like: store, save and persist. All three are used for a different purpose while they may do the same :-)

Related