<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                ## Chapter 6. Enums and Annotations(枚舉和注解) ### Item 38: Emulate extensible enums with interfaces(使用接口模擬可擴展枚舉) In almost all respects, enum types are superior to the typesafe enum pattern described in the first edition of this book [Bloch01]. On the face of it, one exception concerns extensibility, which was possible under the original pattern but is not supported by the language construct. In other words, using the pattern, it was possible to have one enumerated type extend another; using the language feature, it is not. This is no accident. For the most part, extensibility of enums turns out to be a bad idea. It is confusing that elements of an extension type are instances of the base type and not vice versa. There is no good way to enumerate over all of the elements of a base type and its extensions. Finally, extensibility would complicate many aspects of the design and implementation. 枚舉類型幾乎在所有方面都優于本書第一版 [Bloch01] 中描述的 typesafe 枚舉模式。從表面上看,有一個與可擴展性有關的例外,它在字節碼模式下是可能的,但是語言構造不支持。換句話說,使用字節碼模式,可以讓一個枚舉類型擴展另一個枚舉類型;但使用語言特性,則不能這樣。這并非偶然。因為在大多數情況下,枚舉的可擴展性被證明是一個壞主意,主要在于:擴展類型的元素是基類的實例,而基類的實例卻不是擴展類型的元素。而且沒有一種好方法可以枚舉基類及其擴展的所有元素。最后,可擴展性會使設計和實現的許多方面變得復雜。 That said, there is at least one compelling use case for extensible enumerated types, which is operation codes, also known as opcodes. An opcode is an enumerated type whose elements represent operations on some machine, such as the Operation type in Item 34, which represents the functions on a simple calculator. Sometimes it is desirable to let the users of an API provide their own operations, effectively extending the set of operations provided by the API. 也就是說,對于可擴展枚舉類型,至少有一個令人信服的用例,即操作碼,也稱為 opcodes。操作碼是一種枚舉類型,其元素表示某些機器上的操作,例如 [Item-34](/Chapter-6/Chapter-6-Item-34-Use-enums-instead-of-int-constants.md) 中的 Operation 類,它表示簡單計算器上的函數。有時候,我們希望 API 的用戶提供自己的操作,從而有效地擴展 API 提供的操作集。 Luckily, there is a nice way to achieve this effect using enum types. The basic idea is to take advantage of the fact that enum types can implement arbitrary interfaces by defining an interface for the opcode type and an enum that is the standard implementation of the interface. For example, here is an extensible version of the Operation type from Item 34: 幸運的是,有一種很好的方法可以使用枚舉類型來實現這種效果。其基本思想是利用枚舉類型可以實現任意接口這一事實,為 opcode 類型定義一個接口,并為接口的標準實現定義一個枚舉。例如,下面是 [Item-34](/Chapter-6/Chapter-6-Item-34-Use-enums-instead-of-int-constants.md) Operation 類的可擴展版本: ``` // Emulated extensible enum using an interface public interface Operation { double apply(double x, double y); } public enum BasicOperation implements Operation { PLUS("+") { public double apply(double x, double y) { return x + y; } }, MINUS("-") { public double apply(double x, double y) { return x - y; } }, TIMES("*") { public double apply(double x, double y) { return x * y; } }, DIVIDE("/") { public double apply(double x, double y) { return x / y; } }; private final String symbol; BasicOperation(String symbol) { this.symbol = symbol; } @Override public String toString() { return symbol; } } ``` While the enum type (BasicOperation) is not extensible, the interface type (Operation) is, and it is the interface type that is used to represent operations in APIs. You can define another enum type that implements this interface and use instances of this new type in place of the base type. For example, suppose you want to define an extension to the operation type shown earlier, consisting of the exponentiation and remainder operations. All you have to do is write an enum type that implements the Operation interface: 枚舉類型(BasicOperation)是不可擴展的,而接口類型(Operation)是可擴展的,它是用于在 API 中表示操作的接口類型。你可以定義另一個實現此接口的枚舉類型,并使用此新類型的實例代替基類型。例如,假設你想定義前面顯示的操作類型的擴展,包括求冪和余數操作。你所要做的就是寫一個枚舉類型,實現操作接口: ``` // Emulated extension enum public enum ExtendedOperation implements Operation { EXP("^") { public double apply(double x, double y) { return Math.pow(x, y); } }, REMAINDER("%") { public double apply(double x, double y) { return x % y; } }; private final String symbol; ExtendedOperation(String symbol) { this.symbol = symbol; } @Override public String toString() { return symbol; } } ``` You can now use your new operations anywhere you could use the basic operations, provided that APIs are written to take the interface type (Operation), not the implementation (BasicOperation). Note that you don’t have to declare the abstract apply method in the enum as you do in a nonextensible enum with instance-specific method implementations (page 162). This is because the abstract method (apply) is a member of the interface (Operation). 現在可以在任何可以使用 Operation 的地方使用新 Operation,前提是編寫的 API 采用接口類型(Operation),而不是實現(BasicOperation)。注意,不必像在具有特定于實例的方法實現的非可擴展枚舉中那樣在枚舉中聲明抽象 apply 方法(第 162 頁)。這是因為抽象方法(apply)是接口(Operation)的成員。 **譯注:示例如下** ``` public static void main(String[] args) { Operation op = BasicOperation.DIVIDE; System.out.println(op.apply(15, 3)); op=ExtendedOperation.EXP; System.out.println(op.apply(2,5)); } ``` Not only is it possible to pass a single instance of an “extension enum” anywhere a “base enum” is expected, but it is possible to pass in an entire extension enum type and use its elements in addition to or instead of those of the base type. For example, here is a version of the test program on page 163 that exercises all of the extended operations defined previously: 不僅可以在需要「基枚舉」的任何地方傳遞「擴展枚舉」的單個實例,還可以傳入整個擴展枚舉類型,并在基類型的元素之外使用或替代基類型的元素。例如,這里是 163 頁測試程序的一個版本,它執行了前面定義的所有擴展操作: ``` public static void main(String[] args) { double x = Double.parseDouble(args[0]); double y = Double.parseDouble(args[1]); test(ExtendedOperation.class, x, y); } private static <T extends Enum<T> & Operation> void test(Class<T> opEnumType, double x, double y) { for (Operation op : opEnumType.getEnumConstants()) System.out.printf("%f %s %f = %f%n",x, op, y, op.apply(x, y)); } ``` Note that the class literal for the extended operation type (ExtendedOperation.class) is passed from main to test to describe the set of extended operations. The class literal serves as a bounded type token (Item 33). The admittedly complex declaration for the opEnumType parameter (`<T extends Enum<T> & Operation> Class<T>`) ensures that the Class object represents both an enum and a subtype of Operation, which is exactly what is required to iterate over the elements and perform the operation associated with each one. 注意,擴展 Operation 類型(ExtendedOperation.class)的 class 字面量是從 main 傳遞到 test 的,以描述擴展 Operation 類型的 Set。class 字面量用作有界類型標記([Item-33](/Chapter-5/Chapter-5-Item-33-Consider-typesafe-heterogeneous-containers.md))。誠然,opEnumType 參數的復雜聲明(`<T extends Enum<T> & Operation> Class<T>`)確保類對象同時表示枚舉和 Operation 的子類型,而這正是遍歷元素并執行與每個元素相關的操作所必需的。 A second alternative is to pass a `Collection<? extends Operation>`, which is a bounded wildcard type (Item 31), instead of passing a class object: 第二個選擇是傳遞一個 `Collection<? extends Operation>`,它是一個有界通配符類型([Item-31](/Chapter-5/Chapter-5-Item-31-Use-bounded-wildcards-to-increase-API-flexibility.md)),而不是傳遞一個類對象: ``` public static void main(String[] args) { double x = Double.parseDouble(args[0]); double y = Double.parseDouble(args[1]); test(Arrays.asList(ExtendedOperation.values()), x, y); } private static void test(Collection<? extends Operation> opSet,double x, double y) { for (Operation op : opSet) System.out.printf("%f %s %f = %f%n",x, op, y, op.apply(x, y)); } ``` The resulting code is a bit less complex, and the test method is a bit more flexible: it allows the caller to combine operations from multiple implementation types. On the other hand, you forgo the ability to use EnumSet (Item 36) and EnumMap (Item 37) on the specified operations. 生成的代碼稍微不那么復雜,test 方法稍微靈活一些:它允許調用者組合來自多個實現類型的操作。另一方面,放棄了在指定操作上使用 EnumSet([Item-36](/Chapter-6/Chapter-6-Item-36-Use-EnumSet-instead-of-bit-fields.md))和 EnumMap([Item-37](/Chapter-6/Chapter-6-Item-37-Use-EnumMap-instead-of-ordinal-indexing.md))的能力。 Both programs shown previously will produce this output when run with command line arguments 4 and 2: 在運行命令行參數 4 和 2 時,前面顯示的兩個程序都將產生這個輸出: ``` 4.000000 ^ 2.000000 = 16.000000 4.000000 % 2.000000 = 0.000000 ``` A minor disadvantage of the use of interfaces to emulate extensible enums is that implementations cannot be inherited from one enum type to another. If the implementation code does not rely on any state, it can be placed in the interface, using default implementations (Item 20). In the case of our Operation example, the logic to store and retrieve the symbol associated with an operation must be duplicated in BasicOperation and ExtendedOperation. In this case it doesn’t matter because very little code is duplicated. If there were a larger amount of shared functionality, you could encapsulate it in a helper class or a static helper method to eliminate the code duplication. 使用接口來模擬可擴展枚舉的一個小缺點是實現不能從一個枚舉類型繼承到另一個枚舉類型。如果實現代碼不依賴于任何狀態,則可以使用默認實現([Item-20](/Chapter-4/Chapter-4-Item-20-Prefer-interfaces-to-abstract-classes.md))將其放置在接口中。在我們的 Operation 示例中,存儲和檢索與操作相關的符號的邏輯必須在 BasicOperation 和 ExtendedOperation 中復制。在這種情況下,這并不重要,因為復制的代碼非常少。如果有大量的共享功能,可以將其封裝在 helper 類或靜態 helper 方法中,以消除代碼重復。 The pattern described in this item is used in the Java libraries. For example, the java.nio.file.LinkOption enum type implements the CopyOption and OpenOption interfaces. 此項中描述的模式在 Java 庫中使用。例如,`java.nio.file.LinkOption` 枚舉類型實現 CopyOption 和 OpenOption 接口。 In summary, **while you cannot write an extensible enum type, you can emulate it by writing an interface to accompany a basic enum type that implements the interface.** This allows clients to write their own enums (or other types) that implement the interface. Instances of these types can then be used wherever instances of the basic enum type can be used, assuming APIs are written in terms of the interface. 總之,雖然你不能編寫可擴展枚舉類型,但是你可以通過編寫接口來模擬它,以便與實現該接口的基本枚舉類型一起使用。這允許客戶端編寫自己的枚舉(或其他類型)來實現接口。假設 API 是根據接口編寫的,那么這些類型的實例可以在任何可以使用基本枚舉類型的實例的地方使用。 --- **[Back to contents of the chapter(返回章節目錄)](/Chapter-6/Chapter-6-Introduction.md)** - **Previous Item(上一條目):[Item 37: Use EnumMap instead of ordinal indexing(使用 EnumMap 替換序數索引)](/Chapter-6/Chapter-6-Item-37-Use-EnumMap-instead-of-ordinal-indexing.md)** - **Next Item(下一條目):[Item 39: Prefer annotations to naming patterns(注解優于命名模式)](/Chapter-6/Chapter-6-Item-39-Prefer-annotations-to-naming-patterns.md)**
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看