Search code examples
.netdesign-patternsfactory-pattern

What are the benefits of the factory method pattern aside from subclassing?


While using the .NET Color struct, I found myself wondering why Microsoft chose to use the factory method pattern for this struct (knowing that the factory method pattern is mainly used for subclassing and that structs cannot be subclassed).

I gave Wikipedia a try. It confirmed my thoughts, without actually giving out the answer :

Although the motivation behind the factory method pattern is to allow subclasses to choose which type of object to create, there are other benefits to using factory methods, many of which do not depend on subclassing. Therefore, it is common to define "factory methods" that are not polymorphic to create objects in order to gain these other benefits. Such methods are often static.

So, tell me, what are these other benefits of the factory method pattern?

For example, how could I benefit from calling Color myColor = Color.FromArgb(255,255,255) instead of Color myColor = new Color(255,255,255) ?

(note that the second method isn't actually possible since the Point struct has no parameterized constructor because of the factory method pattern it uses)


Solution

  • The main reason why I use such method is because they are effectively named constructors. For example for Color the order in which the components get specified isn't obvious without a name. Usually ARGB is used, but sometimes you also see BGRA or even an entirely different color space like HSV. Putting the used color order into the method name, makes the code more self documenting.

    Another advantage is that static methods support type inference. For example with Tuple<...>, you can simply use Tuple.Create(1,5) instead of the more verbose new Tuple<int,int>(1,5).