gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 19:58:51 34 4
gpt4 key购买 nike

我已经知道实现和接口(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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com