oop - 为什么接口(interface)有用? (哎呀)

标签 oop interface implements

我已经知道实现和接口(interface)的基础知识。我不明白什么时候使用接口(interface)。有接口(interface)的要求是什么?

例子:

/// Interface demo
Interface IDemo
{
    // Function prototype
    public void Show();
}

// First class using the interface
Class MyClass1 : IDemo
{
public void Show()
{
    // Function body comes here
    Response.Write("I'm in MyClass");
}
}

// Second class using the interface
Class MyClass2 : IDemo
{
public void Show()
{
    // Function body comes here
    Response.Write("I'm in MyClass2");
    Response.Write("So, what?");
}
}

这两个类具有相同的函数名称和不同的主体。这也可以在没有接口(interface)的情况下实现。有方法引用的目的是什么?当我扩展一个父类(super class)时,至少我得到了父类(super class)的属性和方法。

请给我一个清晰的解释和一个真实的世界场景,以便我很好地理解。

最佳答案

首先,他们为用户提供了一个合约,因此用户不需要知道使用了什么底层实现,而只需要知道合约。如果底层实现发生变化,这会产生松散耦合。

现实世界的例子

通过这种方式,我们可以使用某些模式,例如策略和命令模式:Using a strategy pattern and a command pattern

Real World Example of the Strategy Pattern

Real world example of application of the command pattern

抽象类和接口(interface)之间的区别

关于抽象类的大部分内容,请参见此处了解不同之处:Interface vs Abstract Class (general OO)

关于oop - 为什么接口(interface)有用? (哎呀),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15939269/

相关文章:

c++ - LNK2019案例如何解决?一切似乎都是正确的

javascript - 在 Typescript 中过滤现有对象属性

c# - List<Interface> 的 object[] 返回 null

class - 我想将我自己的方法添加到一些 Dart 类中

angular - 类错误地实现了接口(interface) 'OnChanges' 。类型中缺少属性 'ngOnChanges'

python - 如何根据Python中的起始行和结束行获取类的范围?

c++ - 在类的函数中使用 'const'

php - 每当我将数据插入数据库时​​,我都会看到需要插入数据的空格

c# - 为什么具有 "where T : class"约束的 Generic<T> 方法接受接口(interface)

java - Java API中 "implements"和 "All Implemented Interfaces"之间的区别