最近几天,我经常遇到“实现接口”这个术语......我知道它是什么,但我想要更多关于它的信息和一些资源。类什么时候实现接口?
实现接口是什么意思?
示例#1:
世界上所有飞机都实现
IPlane
接口。飞机必须有
两个翅膀
发动机
它一定会飞
public interface IPlane
{
void Fly();
void HasTWoWings();
void Engine();
}
class Boeing737 : IPlane // Boeing 737 implements the interface
{
// this means that the Boeing737 MUST have a fly, hastwowings and an engine method.
// the interface doesn't specify HOW the plane must fly. So long as it does fly
// the compiler doesn't care.
public void Fly()
{
Console.WriteLine("Come fly with me, let's fly, let's fly awaaaaaaaay");
}
public void HasTWoWings()
{
Console.WriteLine("I've got two wings");
}
public void Engine()
{
Console.WriteLine("BRrrrrrrrooooooooooooooooooooooooooooooooom!");
}
}
空中客车公司的实施方式可能略有不同。
那这个有什么用呢?
作为客户,我不在乎我买的是什么飞机,只要它能飞、有发动机和两个机翼就行。
这意味着在机场,你可以给我一架波音或空客,这对我来说并不重要。
这种能力 - 使我们能够编写有助于减少维护麻烦的代码。事物对于扩展是开放的,但对于修改是封闭的。
plane = PlaneFactor.getFirstAvailablePlane() # could get an airbus, or boeing
customer = Customer.new
customer.fly_in(plane)
# customer does not care which plane he gets.
接口是一个契约,它指定类必须创建的一组必需方法。
例如:
public interface ITest
{
public void DoSomething(int someInt);
}
public class MyClass : ITest
{
public void DoSomething(int someInt)
{
... Do some stuff
}
}
如果不包含
DoSomething
方法,编译器会抛出错误。
接口是类必须实现的功能规范。当您实现接口时,您向类的任何使用者指定您提供给定接口中定义的功能。例如(在 C# 中):
public interface ISearchable
{
List<object> Search(string query);
}
ISearchable
是一个指定单个方法的接口,理论上,该方法应该为类提供一些搜索功能。现在,任何想要实现搜索功能的类都可以实现 ISearchable
接口:
public class ConcreteSearchable : ISearchable
{
public List<object> Search(string query)
{
// Implementation
}
}
您现在有一个实现您的
ISearchable
接口的类。这提供了几个好处。其一,您已经明确声明了类行为的某一部分。其次,您现在可以多态地处理您的类(以及接口的其他实现)。
例如,如果有许多类型实现
ISearchable
接口,您可以创建一个 SearchableFactory
,它会根据某些参数构造一个具体类型。工厂的消费者不会关心具体类型...只要他们能搜索到就行:
public class SearchableFactory
{
public static ISearchable CreateInstance(string query)
{
if(query.Contains("SELECT"))
return new SqlSearchable();
else
return new ConcreteSearchable();
}
}
接口是类需要实现的方法的列表。这是一种将类的工作方式与类提供的服务分离的方法。
你可以想象一个Stack数据结构。它的界面中可能有以下内容:
push(Node);
Node pop();
Node peek();
现在,如果您使用数组来实现堆栈,您将把索引保存到数组中并使用它来执行操作。如果你有一个链表,你只需保留一个指向头的指针即可。该接口的要点是,只要您的实现提供了所需的方法,您的实现的用户就不需要知道您的实现类如何工作。
Java 和 C# 等一些语言提供显式的 接口 。其他工具(例如 ruby 或 python)允许您使用相同的技术,但不使用关键字强制执行。您可能会听到术语“鸭子打字”。也就是说,如果某个东西实现了正确的接口,那么无论实现如何,它都可以使用。
实现接口意味着实际编写一些代码来实现接口的描述,包括函数名称、属性和返回值。