Search code examples
c#design-patternsdependency-injectionfactory-patternstrategy-pattern

Saving Data with the Factory Pattern?


I've been becoming more familiar with the Factory Pattern (along with Strategy Pattern) and what a great benefit the pattern can have. However, I've been struggling with the following situation:

Previously, I would have done something like the following, where there's a manager class that would build and save a Car. There's no dependency injection here and is a poor implementation, especially when trying to unit test.

public class CarManager
{
    public static Car GetCarFromDatabase(int carId) { return new Car(); }

    public static void SaveCar(Car car) { }
}

I see now how I could have different Factories that build cars for me, whether it be from a database, or wherever! This is great! So, here's my questions:

Q1: It's my understanding that Factories should only build objects, is that correct? If so, what about my second question?

Q2: If I'm following the Factory Pattern for building my objects, how should I go about saving my objects? Is there a different pattern for this, or am I not completely understanding the Factory Pattern?


Solution

  • The Factory pattern is supposed to help with the creation of objects. That is why it is categorized as a "Creation" pattern. To answer your first question, it should not be used to persist objects.

    The Repository pattern is a persistence pattern that should be used for saving objects to some persistence mechanism or retrieving data from a persistence mechanism. This is actually, according to Martin Fowler, an enterprise pattern which should be approached different than the typical design pattern.

    When thinking about your question, you want to look at the S principle in SOLID which states that a class should have a single responsibility, which means that it should have a single reason to change. In this case, when talking about a object that creates objects as well as saves (persists) them, you have a class that has two reasons to change. Now, it might look like it could be a single responsibility because a Repository can retrieve and save objects into your application and the retrieve can look like a factory (and often is a factory object within the repository), but in what you're describing, your object has one too many responsibilities.