“实现接口”到底是什么意思?

rab*_*ne9 4 design-patterns interface class

最近几天,我经常遇到“实现接口”这个术语......我知道它是什么,但我想要更多关于它的信息和一些资源。类什么时​​候实现接口?

BKS*_*eon 5

实现接口是什么意思?

示例#1:

世界上所有的飞机都实现了该IPlane接口。飞机必须有

  1. 两个翅膀

  2. 一个引擎

  3. 它必须飞翔

    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!");
    }
    }
    
    Run Code Online (Sandbox Code Playgroud)

空中客车公司的实施方式可能略有不同。

那么这个有什么用呢?

作为客户,我不在乎我买的是什么飞机,只要它能飞、有发动机和两个机翼就行。

这意味着在机场,你可以给我一架波音或空客,这对我来说并不重要。

这种能力使我们能够编写有助于减少维护麻烦的代码。事物对于扩展是开放的,但对于修改是封闭的。