我应该继承或使用枚举吗?

时间:2010-09-01 03:51:58

标签: language-agnostic oop

我有很多T数组要读。 每个T数组可以表示A,B或C类型的数据。 答: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
    }
}

2 个答案:

答案 0 :(得分:1)

在OOP中,第二种方式更容易被接受。原因是,如果要根据类型(A,B或C)添加行为,在第一种情况下,您必须检查枚举值。在第二种情况下,您将特定行为添加到具体类型A,B和C.如果您决定添加其他类型或删除其中一个类型,在第一种情况下,您将不得不更改类型检查的所有occourances,在第二种情况下如果只是在一个地方发生变化。

答案 1 :(得分:0)

好吧,如果您需要让泛型类只接受一系列特定类型,那么在数组中记录接受的类型可能会更容易。由于您没有指定特定语言,我将使用c#,但我无法保证可以使用其他语言。我想如果语言能够在运行时创建该类型的实例,那么他们也应该具有检查类型的能力

private static List<Type> _acceptedTypes = { typeof(Type1), typeof(Type2) ... }

X(T[] input)
{
   if(!_acceptedTypes.Contains(typeof(T)))
   {
        throw new SomeException();
   }
   ...
}

虽然个人认为这不是真正理想的,因为它是运行时检查(即,当您尝试使用该类时,您只知道它)。能够以通用的方式应用约束会更好,因为.net只有一种类型(在你的情况下没有帮助)。