difference between a repository and factory pattern

23,107

Solution 1

The Factory pattern is for creating objects, while the Repository pattern describes a general method of encapsulating CRUD operations against a data source.

Solution 2

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.

Solution 3

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 :-)

Share:
23,107
Blankman
Author by

Blankman

... .. . blank

Updated on April 12, 2020

Comments

  • Blankman
    Blankman about 4 years

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

  • Saif Khan
    Saif Khan almost 15 years
    You can also say, ...is for creating several families of objects.
  • yardpenalty.com
    yardpenalty.com over 9 years
    So if we had needed to create a relationship between some external services and a local DbContext would designing a factory for this purpose be an efficient way to implement a factory? Then create repositories accordingly within a UOW.
  • Dennis
    Dennis almost 7 years
    Question: Say I need to create an object instance, but I also want to populate that instance with fresh new data from database, aka use the "R" of CRUD while creating an object. What is the resulting pattern called? Is it a Factory that uses Repository as part of object creation?
  • RHa
    RHa over 5 years
    If the object is filled with data from the database, then conceptually it is not a new object, because the data was already there. So I would say it's a Repository.