我正在阅读有关静态工厂方法的文章。静态工厂方法编码技术是只适用于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);
}
}发布于 2019-04-16 13:19:39
是的,它绝对可以应用在C#中,而且这通常是一个好主意--特别是当你想用不同的方法构造一些东西的时候,所有这些方法都来自相同的参数类型。
以TimeSpan为例。它具有工厂方法FromSeconds、FromMinutes、FromHours和FromDays,所有这些方法都接受单个double作为参数类型。
工厂方法模式还允许在某些情况下进行缓存。
发布于 2019-04-16 13:20:53
Static Factory是Factory Method设计模式的一个变体,可以在多种语言中使用,而不仅仅是Java和C#。
它们已经存在于TimeSpan类的C#中,您可以在该类中执行以下操作:
var seconds = TimeSpan.FromSeconds(5);
var minutes = TimeSpan.FromSeconds(25);https://stackoverflow.com/questions/55700934
复制相似问题