代码之家  ›  专栏  ›  技术社区  ›  flakes

创建不可实例化、不可扩展的类

  •  2
  • flakes  · 技术社区  · 7 年前

    我想安排一个班来分组 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");
      }
      ...
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Jonah Williams    7 年前

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