接口与类:定义方法
本文关键字:定义 方法 接口 | 更新日期: 2023-09-27 18:30:47
我对面向对象编程有点陌生,我试图理解这种实践的所有方面:继承、多态性等,但有一件事我的大脑不想完全理解:接口。
我可以理解使用接口而不是类继承的好处(主要是因为一个类不能从多个父级继承),但这就是我卡住的地方:
假设我有这样的东西:
/** 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() { ... }
}
通过在这里使用接口,我必须在每个类中每次声明MoveMethod
、KillMethod
和RenderMethod
......这意味着复制我的代码。一定有什么问题,因为我觉得这并不实用。
那么我应该只在几个类上实现接口吗?还是我应该找到一种方法来混合继承和接口?
接口就像类的契约。如果某个类声明它支持这样的接口,则必须在正确采样时定义它的方法。 接口非常适合公开不容易跨越不同类实现的常见内容。
现在,从您的示例中,最好通过从类和接口进行子类化来组合以防止重复代码。 因此,您可以获取父结构代码常量并根据需要进行扩展。
/** 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() { ... }
}