Search code examples
c#design-patternsinheritanceconstructorfactory-pattern

Creating some instances of the child class in a method of the parent class


I have the following classes:

abstract class Transport{

    protected String name;

    protected Transport(String name){
        this.name=name;
    }

    protected void DoSomething(){
        //Creating some instances of the type of the current instance   
    }   

}

class Bike: Transport {

    public Bike(String name): base(name){

    }

}

class Bus: Transport {

    public Bus(String name): base(name){

    }

}

What I would like to do is to create some instances of the type of the current instance inside the DoSomething method of the Transport class.

How would I go about it?

I can create a static factory method that accepts the name of the child class I would like to create and then pass it the class name of the current instance inside the DoSomething method by using this.GetType().Name.

But is this the best way?

Many thanks to you all.


Solution

  • You can make a protected abstract Transport CreateNew(string name) method in the base class, and override it in the derived classes to call their constructors.