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)
The main reason why I use such method is because they are effectively named constructors. For example for
Colorthe order in which the components get specified isn’t obvious without a name. UsuallyARGBis used, but sometimes you also seeBGRAor even an entirely different color space likeHSV. 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 useTuple.Create(1,5)instead of the more verbosenew Tuple<int,int>(1,5).