Should I subclass or use an enumeration?

I have many T arrays to read. Each array T can represent data of type A, B or C. A: List T B: One T C: Exactly three T

When I read the array T, I can get the list T and determine by reading the first T in the list, whether it is type A, B or C. I was thinking of two possible approaches and would like to know their advantages and disadvantages.

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 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
    }
}
+3
source share
2 answers

. , (A, B C), . A, B C. , , , .

+1

, , , . , #, , lanaguages. , ,

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

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

, (.. ). , .net, ( ).

0

Source: https://habr.com/ru/post/1762579/


All Articles