簡體   English   中英

如何在 Dart 中定義接口?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM