开发者

C# What pattern to use to create a type based on different types?

开发者 https://www.devze.com 2023-02-20 13:21 出处:网络
I have three different objects which act as input to create object A. The three different objects are:

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 Ob开发者_运维问答jectA 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?


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.


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

public class ObjectA
{
   // class code

   public ObjectA(DataRow row) {/*implementation */}
   public ObjectA(ObjectA obj) {/*implementation */}
   public ObjectA(ObjectB obj) {/*implementation */}
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消