Alex Rivera | Logout

Saving Data with the Factory Pattern?

Asked 2010-10-27T16:58:27.273
11

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?

Edit
Report

1 Answer

1

In general, I think you are approaching this from the wrong angle.

You need to identify the problem you are trying to solve, and then look for solutions that fit that problem. It sounds to me more like you have discovered a certain pattern, and then are trying to apply it to every problem you encounter.

The only problem you mention with the code you posted is that it's not easy to unit test. One solution to making classes more testable is to invert their dependencies. So I would start looking at what other classes this class depends on, and start making those injectable dependencies. As a starting point, I would recommend you read up on dependency inversion/inversion of control.

answered 2010-10-27T17:13:37.650

Your Answer