【问题标题】:Interface vs Class : Defining methods [duplicate]接口与类:定义方法
【发布时间】:2015-01-15 03:58:59
【问题描述】:

我对 OO 编程有点陌生,我正在尝试理解这种实践的所有方面:继承、多态性等,但是我的大脑不想完全理解一件事:接口。

我可以理解使用接口而不是类继承的好处(主要是因为一个类不能从多个父类继承),但我遇到了困难:

假设我有这样的事情:

/** a bunch of interfaces **/
public interface IMoveable
{
    void MoveMethod();
}

public interface IKilleable()
{
    void KillMethod();
}

public interface IRenderable()
{
    void RenderMethod();
}

/** and the classes that implement them **/
public class ClassOne : IMoveable
{
    public void MoveMethod() { ... }
}

public class ClassTwo: IMoveable, IKilleable
{
    public void MoveMethod() { ... }
    public void KillMethod() { ... }
}

public class ClassThree: IMoveable, IRenderable
{
    public void MoveMethod() { ... }
    public void RenderMethod() { ... }
}

public class ClassFour: IMoveable, IKilleable, IRenderable
{
    public void MoveMethod() { ... }
    public void KillMethod() { ... }
    public void RenderMethod() { ... }
}

通过在这里使用接口,我必须每次在每个类中声明MoveMethodKillMethodRenderMethod……这意味着复制我的代码。肯定有问题,因为我觉得这不是很实用。

那么我应该只在少数几个类上实现接口吗?或者我应该找到一种混合继承和接口的方法?

【问题讨论】:

  • 可能最好的理解方法是编写单元测试,仅当您将标志传递给FormatHardDrive(bool really) 时,在格式化硬盘驱动器之前验证显示的对话框。实现这样的方法(不必实际销毁硬盘,但类似的东西)并尝试编写测试。
  • here 是我喜欢的一个很好的例子
  • @Jonesy 谢谢它真的很有帮助!

标签: c# class oop methods interface


【解决方案1】:

接口就像一个类的契约。如果某个类声明它支持这样的接口,它必须在你正确采样时定义它的方法。接口非常适合公开不容易跨越不同类实现的常见事物。

现在,从您的示例中,您可能最好通过从一个类和一个接口继承来防止重复代码的组合。因此,您可以获取父结构代码常量并根据需要进行扩展。

/** Based on same interfaces originally provided... and the classes that implement them **/
public class ClassOne : IMoveable
{
    public void MoveMethod() { ... }
}

public class ClassTwo: ClassOne, IKilleable
{
    // Move Method is inherited from ClassOne, THEN you have added IKilleable
    public void KillMethod() { ... }
}

public class ClassThree: ClassOne, IRenderable
{
    // Similar inherits the MoveMethod, but adds renderable
    public void RenderMethod() { ... }
}

public class ClassFour: ClassTwo, IRenderable
{
    // Retains inheritance of Move/Kill, but need to add renderable
    public void RenderMethod() { ... }
}

【讨论】:

  • 这正是我所要求的,谢谢! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-07
  • 2019-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多