[英]How to define interfaces in Dart?
在 Java 中,我可能有一个接口IsSilly
和一个或多个实现它的具体类型:
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 中的这段代码等价于什么?
在仔细阅读有关类的官方文档后,Dart 似乎没有原生interface
类型。 那么,一般的 Dartisan 是如何实现接口隔离原理的呢?
在 Dart 中有一个隐式接口的概念。
每个类都隐式定义了一个接口,该接口包含该类的所有实例成员以及它实现的任何接口。 如果你想创建一个支持B类API而不继承B实现的A类,A类应该实现B接口。
一个类通过在
implements
子句中声明一个或多个接口,然后提供接口所需的 API 来实现一个或多个接口。
所以你的例子可以像这样在 Dart 中翻译:
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 中,每个类都定义了一个隐式接口。 您可以使用抽象类来定义无法实例化的接口:
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
}
}
混淆通常是因为不存在像 java 和其他语言那样的“接口”这个词。 类声明本身就是 Dart 中的接口。
在 Dart 中,每个类都像其他人所说的那样定义了一个隐式接口。那么……关键是:类应该使用 implements 关键字才能使用接口。
abstract class IsSilly {
void makePeopleLaugh();
}
//Abstract class
class Clown extends IsSilly {
void makePeopleLaugh() {
// Here is where the magic happens
}
}
//Interface
class Comedian implements IsSilly {
void makePeopleLaugh() {
// Here is where the magic happens
}
}
abstract class ORMInterface {
void fromJson(Map<String, dynamic> _map);
}
abstract class ORM implements ORMInterface {
String collection = 'default';
first(Map<String, dynamic> _map2) {
print("Col $collection");
}
}
class Person extends ORM {
String collection = 'persons';
fromJson(Map<String, dynamic> _map) {
print("Here is mandatory");
}
}
这是一个类或接口,视情况而定。
abstract class A {
void sayHello() {
print("Hello");
}
void sayBye();
}
B类实现了A接口,所以它必须实现A的所有方法。
class B implements A {
void sayHello() {
print("B say Hello");
}
void sayBye() {
print("B say Bye");
}
}
C类扩展了A类,所以它必须实现A的所有抽象方法。(不是全部)。 C 继承了 A 类的 sayHello() 方法。
class C extends A {
void sayBye() {
print("C say Bye");
}
}
其他答案在告知与方法的接口方面做得很好。
如果您正在寻找具有属性的接口,则可以使用 getter:
abstract class AppColors {
Color get primary;
Color get secondary;
}
class AppColorsImpl implements AppColors {
@override
Color get primary => Colors.red;
@override
Color get primary => Colors.blue;
}
是的,您也可以组合一个接口来同时拥有属性和方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.