Methods of creating an instance of a class inheritor depending on the data

We have a table in the database with suppliers, each supplier has a corresponding handler class, which is an inheritor from the base class. We need to make a generator for creating handlers.

Three ways of organizing came to mind:

  1. switch .. case

  2. Add a column to the table and place the postfixes there, then create an object based on the name of the heir, which should include this postfix

  3. Place the index in the inherited class attribute and create an object using that value

First method:

    public class parcerA: ParcerBace {}

    public class parcerB: ParcerBace {}

    public abstract class ParcerBace
    {
        switch (id)
        {
          case 1: return new parcerA();
          case 2: return new parcerB();
        }
        return null;
    }

Cheap and cheerful, but if there are many of these processors, then we get a long sheet

Second way:

    public class parcerA: ParcerBace {}

    public class parcerB: ParcerBace {}

    public abstract class ParcerBace
    {
        public static ParcerBace creator(string postfix)
        {
            Type tFind = typeof(ParcerBace);
            Type tR = Assembly.GetAssembly(tFind).GetTypes().FirstOrDefault(t => t.IsSubclassOf(tFind) && t.Name== "parcer" + postfix);
            if (tR != null) return (ParcerBace)Activator.CreateInstance(tR);
            return null;
        }
    }

This is a fairly short code, but you need to monitor the correspondence of these postfixes in the database and the names of objects, which generates errors.

The third way:

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    public class IDAttribute : Attribute
    {
        public IDAttribute(int id) 
        {
            this.id = id;
        }
        public int id { get; set; }
    }

    [ID(1)]
    public class parcerA :ParcerBace {}

    [ID(2)]
    public class parcerB : ParcerBace {}

    public abstract class ParcerBace
    {
        public static ParcerBace creator(int id)
        {
            Type tFind = typeof(ParcerBace);
            Type tR = Assembly.GetAssembly(tFind).GetTypes().FirstOrDefault(t => t.IsSubclassOf(tFind) && (t.GetCustomAttribute(typeof(IDAttribute)) as IDAttribute).id == id);
            if (tR != null) return (ParcerBace)Activator.CreateInstance(tR);
            return null;
        }
    }

Which method do you find more convenient? Maybe there is a more convenient method?

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *