我正在阅读静态工厂方法。静态工厂方法编码技术是否仅适用于Java,还是可以应用于C#.Net吗?似乎更像是Java的东西。
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);
}
}
是的,它绝对可以在C#中应用,并且它通常是一个好主意 - 特别是如果你想要构造某些东西的各种方式,都来自相同的参数类型。
举个例子,看看TimeSpan
。这有工厂方法FromSeconds
,FromMinutes
,FromHours
,FromDays
所有这些都接受单个double
作为参数类型。
工厂方法模式也允许在某些情况下进行缓存。
Static Factory
是Factory Method设计模式的变体,可以用于各种语言,而不仅仅是Java和C#。
它们已经存在于TimeSpan
类的C#中,您可以在其中执行以下操作:
var seconds = TimeSpan.FromSeconds(5);
var minutes = TimeSpan.FromSeconds(25);