I am reading about the static factory method. Does Static factory method coding technique only apply to Java, or can it be applied to C# .Net also? Seems to be more of a Java thing.
https://dzone.com/articles/constructors-or-static-factory-methods
class Color {
private final int hex;
static Color makeFromRGB(String rgb) {
return new Color(Integer.parseInt(rgb, 16));
}
static Color makeFromPalette(int red, int green, int blue) {
return new Color(red << 16 + green << 8 + blue);
}
static Color makeFromHex(int h) {
return new Color(h);
}
private Color(int h) {
return new Color(h);
}
}
Yes, it can definitely be applied in C#, and it's often a good idea - particularly if there are various ways that you want to construct something, all from the same parameter types.
As an example, look at TimeSpan
. That has factory methods FromSeconds
, FromMinutes
, FromHours
, FromDays
all of which accept a single double
as the parameter type.
The factory method pattern also allows for caching in some situations, too.