The Gang-of-Four design patterns have an entire category of creational patterns, to handle the complexities of creating objects. And yes, it can get complicated, especially when we think in terms of the single-responsibility principle. Often, creating an instance of an class is itself so complex that we need a new class to do it.

Thus, we have the Factory pattern. And the Abstract Factory Pattern. And the Abstract Factory Factory Abstract Provider Bean pattern, if you’re using Spring. The purpose of these patterns is to add indirection between the client, calling code, and the creation of the objects- different concrete implementations can be instantiated, without the client code needing to worry about what actual type it received. Polymorphism wins the day. Code is more loosely coupled, because the client code never needs to name the concrete type it uses.

Unless you want to do it wrong, in which case Jen M found this particular solution:

public abstract class TaskBase
{
        public static TaskBase CreateInstance(
                Manager manager,
                Type TaskType)
        {
                object[] args = {manager, -1};

                return Activator.CreateInstance(TaskType, args) as TaskBase;
        }

        public static TaskBase CreateInstance(
                Manager manager,
                int taskId,
                string fullyQualifiedTypeName)
        {
                var TaskType = TypeLoader.GetType(fullyQualifiedTypeName, true);

                object[] args = {manager, taskId};

                var taskInstance = Activator.CreateInstance(TaskType, args) as TaskBase;

                return taskInstance;
        }
}

In this version, you can specify the concrete child of TaskBase that you want an instance of, and this will helpfully call the constructor for you. That means you could write:

var task = TaskBase.CreateInstance(mgr, TypeOf(MyDll.MyPackage.BasicTask))

Which is obviously far more loosely coupled than:

var task = new BasicTask(mgr);

As Jen puts it: “Some of the code I see makes me want to quit my job and go hunt down the people who wrote it. This is one of those instances.” Instead, Jen replaced this code with an actual version of the Factory pattern.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!