OOP模式 - 使用抽象反射很多。这是一个糟糕的模式,我陷入其中?

时间:2017-07-21 19:10:50

标签: c# oop inheritance reflection abstract-class

最近我一直在使用这种模式:

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

...而且,我的意思是,代码很好而且整洁......但它确实意味着我正在使用反射。

例如,我正在开发一个通过命令行工作的新进程,而不是需要处理许多不同的请求类型,并发现自己使用这种模式,有点像这样:

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 ...
    }
}

有没有更好的方法来构建它?我不是担心反思的开销......但我意识到如果有更好的方法,我应该养成以正确的方式做到这一点的习惯:-)

1 个答案:

答案 0 :(得分:1)

我更愿意这样做。我不确定你的用例中你所做的是“错误的”(也许是一个高级大师可以帮忙)但如果你担心反射的开销(What is the "cost" of .NET reflection?)那么它是有意义的像这样明确地编码:

public static class RequestTypeConst
{
    public const Query = "Query";
}

class Handler
{
    protected IRequest Request { get; set; }

    public Handler(IRequest request) 
    { 
        Request = request;
    }

    public void HandleRequest(string requestType)
    {
        if (requestType == RequestTypeConst.Query)
        {
            Request.Query();
        }
    }
}

interface IRequest
{
    List<string> Query();
}

class Request : IRequest
{
    public List<string> Query()
    {
        /** do something **/
        return new List<string>();
    }
}

var handler = new Handler(new Request());
hanlder.HandleRequest("Query");