首页 > 解决方案 > 创建一个不可实例化、不可扩展的类

问题描述

我想创建一个类来对一些static const值进行分组。

// SomeClass.dart
class SomeClass {
  static const SOME_CONST = 'some value';
}

dart 中防止依赖代码实例化此类的惯用方法是什么?我还想阻止扩展到此类。在Java我会做以下事情:

// SomeClass.java
public final class SomeClass {
    private SomeClass () {}
    public static final String SOME_CONST = 'some value';
}

到目前为止,我所能想到的只是抛出一个Exception,但我希望有编译安全性,而不是在运行时停止代码。

class SomeClass {
  SomeClass() {
    throw new Exception("Instantiation of consts class not permitted");
  }
  ...

标签: classinheritancedartconstants

解决方案


为您的类提供一个私有构造函数将使它只能在同一个文件中创建,否则它将不可见。这也可以防止用户在其他文件中扩展或混入该类。请注意,在同一个文件中,您仍然可以扩展它,因为您仍然可以访问构造函数。此外,用户将始终能够实现您的类,因为所有类都定义了一个隐式接口。

class Foo {
  /// Private constructor, can only be invoked inside of this file (library).
  Foo._();

}

// Same file (library).
class Fizz extends Foo {
  Fizz() : super._();
}

// Different file (library).
class Bar extends Foo {} // Error: Foo does not have a zero-argument constructor

class Fizz extends Object with Foo {} // Error: The class Foo cannot be used as a mixin.

// Always allowed.
class Boo implements Foo {}

推荐阅读