Home > Back-end >  Create variable of class without the parameters of it's constructor
Create variable of class without the parameters of it's constructor

Time:03-31

I have a BaseClass with a constructor and some parameters and then I want to do a strategy where depending of an enum, it creates one derived class or another (of that BaseClass), but with the same parameters. Is there any way to refactor this ? Thanks !

public enum GameMode
{
    ModeA,
    ModeB
}

public abstract class BaseClass
{
    public BaseClass(int a, string b, char c)
    {
        
    }
}

public class FirstGameMode : BaseClass
{
    public FirstGameMode(int a, string b, char c) : base(a, b, c)
    {
        
    }
}

public class SecondGameMode: BaseClass
{
    public SecondGameMode(int a, string b, char c) : base(a, b, c)
    {
    }
}

public class TestingPurpose
{
    private GameMode _gameMode;
    private BaseClass _baseClass;
    
    public void Init()
    {
        if (_gameMode == GameMode.ModeA)
        {
            // They use the same variables !
            _baseClass = new FirstGameMode(5, "Hello", 'c');
        }
        else
        {
            // They use the same variables !
            _baseClass = new SecondGameMode(5, "Hello", 'c');
        }
    }
}

I tried with some reflection but still I couldn't do it.

I would like to have something like

    public void Init()
    {
        BaseMatchMode type;
        if (_gameMode == GameMode.ModeA)
        {
            type = typeof(FirstGameMode);
        }
        else
        {
            type = typeof(SecondGameMode);

        }
        _baseClass = new type(5, "Hello", 'c');
    }

CodePudding user response:

You could use a factory delegate method;

Func<int a, string b, char c, BaseClass> factory;
if (_gameMode == GameMode.ModeA)
{
      factory= (a, b, c) => new FirstGameMode(a, b, c);
}
else
{
    factory= (a, b, c) => new SecondGameMode(a, b, c);
}
_baseClass = factory(5, "Hello", 'c');

For such an simple example it would probably be easier to just skip the factory method and create your objects directly. But this technique is sometimes useful if you want to add some abstraction between components.

You could also create a factory class instead of just using a delegate. There are also dependency injection (DI) / Inversion of Control (IoC) frameworks that are intended to solve the problem of specifying what implementation of interfaces/base classes other components should use.

  • Related