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.
Static Factory
is a variation on the Factory Method design pattern and can be used in a variety of languages, not just Java and C#.
They already exist in C# on the TimeSpan
class where you can do the following:
var seconds = TimeSpan.FromSeconds(5);
var minutes = TimeSpan.FromSeconds(25);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.