views:

140

answers:

2

Does the Factory Method pattern (not to be confused with the Factory or Abstract Factory patterns) violate the Open/Closed principle?

Update: To clarify, I'm referring to the scenario where a concrete class has static factory methods on it. For example (this is from the Wikipedia page on FMP):

class Complex 
{
    public static Complex fromCartesian(double real, double imag) {
        return new Complex(real, imag);
    }

    public static Complex fromPolar(double modulus, double angle) {
        return new Complex(modulus * cos(angle), modulus * sin(angle));
    }

    private Complex(double a, double b) {
       //...
    }
}

Doesn't the private constructor prevent the class from being subclassed, i.e. extended?

Wouldn't the class have to be modified to support new factory methods? For example, if the class initially only had fromCartesian and later fromPolar was needed, didn't the class have to be modified to support this?

Don't both of these violate Open/Closed?

+1  A: 

Nope. From your Wikipedia link:

software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification

Overriding the factory method is extension. You're creating a new class. You don't change the existing class. You have to substitute (via configuration of your IoC container hopefully) the subclass for the original.

noah
+1  A: 

No, it doesn't violate the Open/Closed principle at all.

Open/Closed means you can modify the way a system works without modifying the code that already exists. You can extend the code and use it in different ways, but the old code is still in tact and doesn't need to be re-tested.

The Factory Method pattern will create a different type of object based on specified parameters. Factory Method actually works well with the Open/Closed principle if done correctly. However, if you create a new class and then want the Factory Method to create a new object of that type you would have to change the Factory Method.

Although, if you had some kind of configuration file or something of that sort that is read in by the Factory Method then you wouldn't have to change the Factory Method ... just the config file that then dictates what object will be created by the Factory Method.

Brian T Hannan

related questions