我有很多 T 数组要读取。
每个 T 数组可以表示 A、B 或 C 类型的数据。
A:T列表
B:单T
C:正好三个T
当我读取一个 T 数组时,我将能够得到一个 T 的列表,并通过读取列表中的第一个 T 来确定它是 A、B 还是 C 类型。
我想到了两种可能的方法,想知道它们的优缺点。
1)
enum {A, B, C};
class X {
enum dataType;//A, B or C
List<T> data;//just store all as list of T
//other essential methods/properties
//throws exception if an instance cannot fit into either A, B or C.
X(T[] input)
{
//read input
}
}
2)
abstract class X
{
abstract int length{get;}
//and other common essential methods/properties
}
class A : X
{
List<T> data;
}
class B : X
{
T data;
}
class C : X
{
T data1, data2, data3;
}
class ConcreteX: X
{
List<T> data;
ConcreteX(T[] input)
{
//reads input and stores T(s) into data
}
}
class XFactory
{
getX(T[] input)
{
ConcreteX conX = new ConcreteX(input);
//depending on whether it's A, B or C, create an instance of A, B,
//or C and map the corresponding fields from conX to the instance.
//return that instance
}
}
最佳答案
在 OOP 中,第二种方式更容易接受。原因是,如果您要根据类型(A、B 或 C)添加行为,则在第一种情况下,您必须检查枚举值。在第二种情况下,您将特定行为添加到具体类型 A、B 和 C。如果您决定添加另一种类型或删除其中一个,在第一种情况下,您必须更改类型检查的所有出现,在第二种情况下在这种情况下,变化只发生在一个地方。
关于language-agnostic - 我应该继承还是使用枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3614922/