我有很多T数组要读取。
每个T数组可以表示A,B或C类型的数据。
答:T的清单
B:一个T
C:正好三个

当我读取一个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/

10-11 21:28