开发者

Design Problem - Common base class and different return types

开发者 https://www.devze.com 2022-12-09 17:21 出处:网络
What I have? I have an abstract class QueryExecutor and many classes inheriting from it, I have just given two of them. The logic of constructing the result object is same but, each inherited class re

What I have? I have an abstract class QueryExecutor and many classes inheriting from it, I have just given two of them. The logic of constructing the result object is same but, each inherited class returns a different collection - some of them are in Syst开发者_开发知识库em.Web.UI.WebControls namespace and some are custom collection classes.

abstract class QueryExecutor
{
    abstract object Execute();

    //Common methods for construction of query
}

class SqlQueryExecutor : QueryExecutor
{
    public object Execute()
    {
        ProfileNodeCollection nodes = new ProfileNodeCollection();
        //Construct nodes
        return nodes;
    }
}

class CamlQueryExecutor : QueryExecutor
{
    public object Execute()
    {
        TreeNodeCollection nodes = new TreeNodeCollection();
        //Construct nodes
        return nodes;
    }
}

What I want?

I thought of having a factory which instantiates appropriate child class and return the result. In the above design, I need to cast the result coming from QueryExecutor.Execute() method. Which I don't want to do.

What problem am I facing?

Since return types are different in child classes (and some are in System.Web.dll), is the above design appropriate for this problem?

Is there any other approach I have to follow?


Why not use generics to do this?

abstract class QueryExecutor<T>
    {
        public abstract T Execute();

        //Common methods for construction of query 
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消