Creating a Non-Instantiable, Non-Extendable Class

北城以北 提交于 2020-01-02 08:41:12

问题


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

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

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");
  }
  ...

回答1:


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


来源:https://stackoverflow.com/questions/51344769/creating-a-non-instantiable-non-extendable-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!