接口与类:定义方法

时间:2014-11-18 03:47:23

标签: c# class oop methods interface

我对OO编程有点新意,我试图理解这种实践的所有方面:继承,多态等等,但有一件事我的大脑不想完全理解:接口。< / p>

我可以理解使用接口而不是类继承的好处(主要是因为一个类不能从多个父级继承)但是这就是我被困住的地方:

让我说我有这样的事情:

/** 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 ......这意味着复制我的代码。一定有什么不对的,因为我觉得这不太合适。

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

1 个答案:

答案 0 :(得分:2)

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

现在,从您的示例中,您可能最好通过从类中进行子类化以及接口来进行组合以防止重复代码。因此,您可以使父结构代码保持不变并根据需要进行扩展。

/** 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() { ... }
}
相关问题