Lately I've been using this sort of pattern a lot:
abstract class myBaseClass
{
//some common methods/properties/etc that all inheritors would share
//some abstract methods/properties/etc that inheritors must implement
protected abstract bool DoIHandleThisSortOfRequest(...);
public static myBaseClass GetHandler()
{
// some reflection to enumerate through classes
// that inherit from myBaseClass, and use
// something like DoIHandleThisSortOfRequest() on each
}
}
... and, I mean, the code is nice and neat... but it does mean I'm using reflection quite a bit.
For example, I'm currently working on a new process that works via command line than needs to handle a lot of different request types, and found myself using this sort of pattern, kinda like this:
abstract class FunctionRequest
{
protected abstract string RequestName { get; }
public abstract void Run();
public static FunctionRequest GetHandler(string requestName)
{
// use reflection to get list of classes deriving from FunctionRequest
// find one that has instance.RequestName equals requestName
}
}
public class QueryRequest : FunctionRequest
{
protected override string RequestName { get { return "Query"; } }
public override void Run()
{
// ... code ...
}
}
Is there a better way to structure this? I'm not too worried about the overhead of Reflection on this... but I realize if there's a better way to do it, I should get in the habit of doing it the right way :-)
Aucun commentaire:
Enregistrer un commentaire