C# 使用什么模式来创建基于不同类型的类型?
我有三个不同的对象,它们充当创建对象 A 的输入。这三个不同的对象是:
- DataRow
- 对象 A(当我想创建副本时)
- 对象 B(看起来像对象 A,但不同,不是子类型)
现在我对象 A 上有一个静态方法,如下所示:
public class ObjectA
{
// class code
public static ObjectA CreateFromType(DataRow row) {/*implementation */}
public static ObjectA CreateFromType(ObjectA obj) {/*implementation */}
public static ObjectA CreateFromType(ObjectB obj) {/*implementation */}
}
这是一个好方法吗?这是违反 OCP 的代码味道吗?你会如何实施这个?
I have three different objects which act as input to create object A. The three different objects are:
- DataRow
- object A (when I want to create a copy)
- Object B (looks like object A, but is different and not a subtype)
Now I have a static method on object A that looks like this:
public class ObjectA
{
// class code
public static ObjectA CreateFromType(DataRow row) {/*implementation */}
public static ObjectA CreateFromType(ObjectA obj) {/*implementation */}
public static ObjectA CreateFromType(ObjectB obj) {/*implementation */}
}
Is this a good way? Is this a code smell that violates OCP? How would you implement this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么不提供适当的构造函数而不是工厂方法?是否存在可以“默认创建”
ObjectA
的第四种情况?构造函数作为一种方法具有明显的优势,因为当有人要创建一个对象时,它们是
ObjectA
公共接口中最明显的部分。如果实例的主要场景是以您提到的方式之一创建的,我强烈建议使用构造函数。特别提及“克隆”构造函数:如果程序集中有其他可克隆的类,则定义自己的 IClonable 派生以及具有明确定义的语义(浅层或深层)可能是有意义的克隆)并使用该方法而不是复制构造函数。
Why not provide appropriate constructors instead of factory methods? Is there a fourth scenario where
ObjectA
can be "default-created"?Constructors have a definite advantage as an approach in that they are the most visible part of
ObjectA
's public interface when someone is about to create one. If the main scenario for instances is to be created in one of the ways you mention, I 'd stronly suggest constructors.A special mention for the "clone" constructor: if you have other classes in your assembly which are clonable, it might make sense to define your own
IClonable
derivative as well with well-defined semantics (shallow or deep clone) and use that approach instead of the copy constructor.为什么不在 ObjectA 上创建不同的构造函数呢?或者显式或隐式运算符?我认为您的情况不需要静态方法。
Why not just create different constructors on
ObjectA
? Or explicit or implicit operators? I don't see the need for static methods in your case.看起来不错,尽管你也可以使用构造函数
Looks OK, though you could also use constructors
ObjectA
可以自己创建并独立初始化吗?我倾向于让你的构造函数不进行这种数据传输,而是创建对象方法来初始化 3 种不同场景的数据。如果您希望从 ObjectA 继承并专门化数据传输,这也可以提高灵活性。
Can
ObjectA
be created on its own and initialized independently? I would be inclined to leave your constructor devoid of this data transfer, and instead create object methods to initialize the data for your 3 different scenarios.This also improves flexibility should you wish to inherit from ObjectA and specialize the data transfer.