在派生类中设计具有相同名称的不同签名

时间:2012-08-27 06:58:51

标签: design-patterns inheritance .net-3.5

我希望实现静态调用,例如File.XLS.Export(columnNames, dbNames);File.CSV.Export(delimiter, columnNames, dbNames);

到现在为止,我设计了一个抽象类,让CSV和XLS继承它。 如您所见,使用CSV导出时可能需要不同的签名。我可以做一个重载,但我不想在XLS导出中看到那个重载,因为它在那里完全没用。

那么如何在XLS导出中隐藏这个特定的实现呢?我可以使用任何模式吗?

3 个答案:

答案 0 :(得分:2)

我会说查看Liskov Substitution Principle。归结为同一抽象的两个具体实现应该是可以互换的。如果在示例中将XLS交换为CSV实现,则必须更改源代码。

 // Some client code
 // it has to be aware of differing implementations, so if this changes to CSV
 // this code changes
 File exported = XLS.export(columnNames, dbNames);

我不赞成使用静态方法,而是赞成一种方法,其中XLSExporter和CSVExporter都派生自相同的基类并具有相同的完全相同的接口。我是一个Java人,但你应该能够理解这个想法:

 public interface Exporter {
    public File export();
 }

 public class XLSExporter implements Exporter {
    public XLSExporter(String[] columns, String[] databases) // specifics go in constructor

    public File export() // ...
 }

 public class CSVExporter implements Exporter {
    public CSVExporter(String delim, String[] columns, String[] databases) // specifics go in constructor

    public File export() // ...
 }

现在,Exporter的客户不需要知道不同的参数。他们只是出口任何东西。这将使您的代码具有灵活性和可维护性。

 // new client code
 // doesn't care about what kind of exporter it is, it just executes what it's given
 File exported = exporter.export();

答案 1 :(得分:0)

经过一些方法后,我将使用ExtensionMethods。它似乎最适合我们的环境。

答案 2 :(得分:0)

如果您需要两个函数是静态的,那么您不需要继承。只需创建一个类,并在其中粘贴两个不同的静态函数,具有不同的签名和不同的实现。我认为你过度设计了它,特别是在考虑现有代码库强加给你的唯一约束时,将函数设置为静态。

相关问题