简体   繁体   中英

Interface abstract Generics C# OO

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?

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM