[Solved] Polymorphic object creation without IF condition


You want to make collection of records, by string code of object type, and parameters.

One of many way to do it – use builder.

Firstly we need to configurate builder:

        var builder = new RecordBuilder()
            .RegisterBuilder("document", (source, value) => new Document(source, value))
            .RegisterBuilder("headlines", (source, value) => new Headlines(source, value));

here we specify how to build record with code “document” and “headlines”.

To build a record call:

        builder.Build("document", "source", 1);

Builder code can by something like this
(here we look if we know how to build record of the passed type and make it):

public class RecordBuilder
{
    public Records Build(string code, string source, int value)
    {
        Func<string, int, Records> buildAction;

        if (recordBuilders.TryGetValue(code, out buildAction))
        {
            return buildAction(source, value);
        }

        return null;
    }

    public RecordBuilder RegisterBuilder(string code, Func<string, int, Records> buildAction)
    {
        recordBuilders.Add(code, buildAction);
        return this;
    }

    private Dictionary<string, Func<string, int, Records>> recordBuilders = new Dictionary<string, Func<string, int, Records>> ();
}


public class Document : Records
{
    public Document(string source, int value) : base(ContentTypesString.DocumentNew, source, value)
    {
    }
}

public class Headlines : Records
{
    public Headlines(string source, int value) : base(ContentTypesString.HeadlinesNew, source, value)
    {
    }
}

2

solved Polymorphic object creation without IF condition