language-agnostic - 我应该继承还是使用枚举?

标签 language-agnostic oop

我有很多 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/

相关文章:

language-agnostic - 给定 R、G、B 三元组和因子 F,我如何计算颜色的 “watermark” 版本?

language-agnostic - 如何编写While循环

java - spring 中的单例可以有静态方法吗?

c++ - 在 C++ 中编译类的代码时,控制流的顺序是什么?

language-agnostic - 从方法返回子类或接口(interface)实现的最佳实践是什么?

algorithm - 找到小于 x 的 10 的最大幂的最快方法

algorithm - 最小封闭球体的弹跳气泡算法

python - 如何正确组织这段代码?

java - 参数列表中引用变量占位符的术语

c# - 公共(public)变量与带有访问器的私有(private)变量