Home > Enterprise >  Interface abstract Generics C# OO
Interface abstract Generics C# OO

Time:09-06

I am implementing a set of C# classes /interfaces which should be reflect act as an action based on an input string. Basically, given an input string, the set of classes/ interfaces should identify the input and act as an action class.

I would like to use generics, whatever pattern that makes it comfortable to use.

Input examples:

1) ABC-{RandNumber(3)}
2) {CurrentNumber}
3) QWE-{RandString(5)}
4) ABY-{Date(yyyy)}

The interface represents an Action:

public interface IAction 
{
}

The actions classes represents the contract actions

public abstract class Action: IAction
{
}

public sealed class RandonNumberAction : Action
{
}

public sealed class RandonStringAction : Action
{
}

Now here it comes the question. What’s the best approach to map the input string to the real concrete to action classes? Reflection? generics?

CodePudding user response:

Here Strategy pattern can be used to select an algorithm at runtime. However, it is necessary to store these algorithms somewhere. I think, this is a place where simple factory can be used.

So your classes look like this:

public interface IAction
{
}


public abstract class Action : IAction
{
}


public sealed class RandonNumberAction : Action
{
}


public sealed class RandonStringAction : Action
{
}

Then we need a place to store these strategies and take it when it is necessary. This is a place where simple factory can be used.

public class ActionFactory
{
    private Dictionary<string, Action> _actionByType =
        new Dictionary<string, Action>()
    {
        { "foo", new  RandonNumberAction() },
        { "bar", new RandonStringAction()  }
    };

    public Action GetInstanceByInput(string input) => _actionByType[input];
}
  • Related