如何在Dart中定义接口? [英] How to define interfaces in Dart?

查看:452
本文介绍了如何在Dart中定义接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我可能有一个接口 IsSilly 以及一个或多个实现它的具体类型:

In Java, I might have an interface IsSilly and one or more concrete types that implement it:

public interface IsSilly {
    public void makePeopleLaugh();
}

public class Clown implements IsSilly {
    @Override
    public void makePeopleLaugh() {
        // Here is where the magic happens
    }
}

public class Comedian implements IsSilly {
    @Override
    public void makePeopleLaugh() {
        // Here is where the magic happens
    }
}

Dart中此代码的等价物是什么?

What's the equivalent to this code in Dart?

在仔细阅读官方 docs ,似乎Dart没有本机接口类型。那么,平均Dartisan如何完成界面隔离原则?

After perusing the official docs on classes, it doesn't seem that Dart has a native interface type. So, how does the average Dartisan accomplish the interface segregation principle?

推荐答案

在Dart中有隐式接口


每个类都隐式定义一个接口,该接口包含类的所有实例成员及其实现的任何接口。如果你想创建一个支持B类API的A类而不继承B的实现,那么A类应该实现B接口。

Every class implicitly defines an interface containing all the instance members of the class and of any interfaces it implements. If you want to create a class A that supports class B’s API without inheriting B’s implementation, class A should implement the B interface.

一个类通过声明来实现一个或多个接口它们在中实现子句,然后提供接口所需的API。

A class implements one or more interfaces by declaring them in an implements clause and then providing the APIs required by the interfaces.

所以你的例子可以在Dart中翻译如下:

So your example can be translate in Dart like this :

abstract class IsSilly {
  void makePeopleLaugh();
}

class Clown implements IsSilly {
  void makePeopleLaugh() {
    // Here is where the magic happens
  }
}

class Comedian implements IsSilly {
  void makePeopleLaugh() {
    // Here is where the magic happens
  }
}

这篇关于如何在Dart中定义接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆