【问题标题】:Design different signatures with same name in derived classes在派生类中设计具有相同名称的不同签名
【发布时间】:2012-08-27 06:58:51
【问题描述】:

我想实现像File.XLS.Export(columnNames, dbNames);File.CSV.Export(delimiter, columnNames, dbNames);这样的静态调用

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

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

【问题讨论】:

    标签: design-patterns inheritance .net-3.5


    【解决方案1】:

    我想说看看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();
    

    【讨论】:

    • 感谢您的建议,但我需要将其设为静态,因为我们现有的所有基本功能都是静态的。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      如果您需要这两个函数是静态的,那么您不需要继承。只需创建一个类并在其中添加两个不同的静态函数,它们具有不同的签名和不同的实现。我认为您对其进行了过度设计,尤其是在考虑现有代码库对您施加的唯一约束以使功能静态时。

      【讨论】:

      • 你是对的。这就是为什么我得出使用扩展方法的结论。我想要的只是两个类中的相同方法名称。但现在我要(重载).ToXLS 和 .ToCSV
      猜你喜欢
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 2022-01-25
      • 2017-01-11
      • 1970-01-01
      相关资源
      最近更新 更多