设计问题-通用基类和不同的返回类型 [英] Design Problem - Common base class and different return types

查看:93
本文介绍了设计问题-通用基类和不同的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有什么?
我有一个抽象类 QueryExecutor 和许多继承自它的类,我只给了两个他们。构造结果对象的逻辑是相同的,但是每个继承的类都返回不同的集合-其中一些位于 System.Web.UI.WebControls 命名空间中,而某些则是自定义集合类。

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

我想要什么?

我想到一家工厂可以实例化适当的子类并返回结果。在上面的设计中,我需要强制转换 QueryExecutor.Execute()方法的结果。我不想做什么。

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.

我遇到了什么问题?

由于子类的返回类型不同(有些在 System.Web.dll 中),以上设计是否适合此问题?

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?

推荐答案

为什么不使用泛型来做

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

        //Common methods for construction of query 
    }

这篇关于设计问题-通用基类和不同的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆