简体   繁体   English

Dart:隐式接口和抽象 class 之间的区别

[英]Dart: difference between implicit interface and abstract class

I am unable to understand the use of 'abstract' keyword in dart.我无法理解 dart 中“抽象”关键字的使用。 If any class when implemented can act implicitly as an abstract class, what does the abstract keyword has to offer?如果任何 class 在实现时可以隐式地充当抽象 class,那么抽象关键字必须提供什么?

Non-abstract classes cannot have abstract methods.非抽象类不能有抽象方法。 So, if you define an interface without implementation, you have to use an abstract class.所以,如果你定义一个没有实现的接口,你必须使用一个抽象的 class。

From thedocumentation :文档中:

// This class is declared abstract and thus
// can't be instantiated.
abstract class AbstractContainer {
  // Define constructors, fields, methods...

  void updateChildren(); // Abstract method.
}

In other words, an abstract class doesn't necessarily provide a default implementation of its interface.换句话说,抽象 class 不一定提供其接口的默认实现。

Example例子

A pure abstract class can be useful as a specification (when the user of this class doesn't know or is not interested in specific implementation).纯抽象 class 可用作规范(当此 class 的用户不知道或对具体实现不感兴趣时)。 One of the common examples can be a repository:一个常见的例子可以是存储库:

abstract class UserRepository {
  Future<void> save(User user);
  Future<User> load(String id);
}

class UseCase {
  UseCase(this.repository);

  final UserRepository repository;
}

In this example, UseCase doesn't care about the specific implementation of the repository (and it shouldn't if we speak about Clean Architecture or another layered architecture approach).在这个例子中, UseCase不关心存储库的具体实现(如果我们谈论清洁架构或其他分层架构方法,它也不应该关心)。 It just defines that, for it to work, it needs a repository class implementing this specific interface.它只是定义了,为了让它工作,它需要一个存储库 class 来实现这个特定的接口。

Somewhere in the infrastructure layer, you can define the implementation of this repository, eg using SharedPreferences :在基础设施层的某处,您可以定义此存储库的实现,例如使用SharedPreferences

class SharedPreferencesUserRepository implements UserRepository {
  @override
  Future<void> save(User user) {
    // Implementation
  }

  @override
  Future<User> load(String id) {
    // Implementation
  }
}

And when you create a UseCase instance, you pass the concrete class implementing the interface.当你创建一个UseCase实例时,你传递了实现接口的具体 class 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM