创建一个不可实例化,不可扩展的类 [英] Creating a Non-Instantiable, Non-Extendable Class

查看:123
本文介绍了创建一个不可实例化,不可扩展的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to make a class to group some static const values.

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

在Dart中,防止依赖代码实例化此类的惯用方式是什么?我也想防止扩展到此类。在 Java 中,我将执行以下操作:

What is the idiomatic way in dart to prevent dependent code from instantiating this class? I would also like to prevent extension to this class. In Java I would do the following:

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

到目前为止,我所能想到的就是抛出例外,但我希望具有编译安全性,而不是在运行时暂停代码。

So far all I can think of is throwing an Exception, but I'd like to have compile safety as opposed to halting code in run-time.

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


推荐答案

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

Giving you class a private constructor will make it so it can only be created within the same file, otherwise it will not be visible. This also prevents users from extending or mixing-in the class in other files. Note that within the same file, you will still be able to extend it since you can still access the constructor. Also, users will always be able to implement your class, since all classes define an implicit interface.

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 {}

这篇关于创建一个不可实例化,不可扩展的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆