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

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

问题描述

我想创建一个类来对一些 static 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';
}

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

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天全站免登陆