class - 创建一个不可实例化、不可扩展的类
问题描述
我想创建一个类来对一些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");
}
...
解决方案
为您的类提供一个私有构造函数将使它只能在同一个文件中创建,否则它将不可见。这也可以防止用户在其他文件中扩展或混入该类。请注意,在同一个文件中,您仍然可以扩展它,因为您仍然可以访问构造函数。此外,用户将始终能够实现您的类,因为所有类都定义了一个隐式接口。
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 {}
推荐阅读
- python - Macbook 上的 Python 安装中断
- java - 每个单独的行如何容纳不同数量的项目?
- python - Selenium 是否适用于基于 Oracle 的网站?
- firebase - 登录 Firebase/Flutter
- javascript - 如何从 .aspx 页面 javascript 调用 C# 方法后面的 Web 窗体代码
- html - 侧边菜单宽度动画?
- hibernate - 如何解决:无法构建 Hibernate SessionFactory 原因:org.hibernate.HibernateException:命名查询中的错误
- django - 图像不会显示 Django3 服务 Angular8
- laravel - 试图从 API 获取 json 中非对象的属性
- server-sent-events - 如何在 Quarkus 中设置服务器发送事件 (SSE) 的事件名称