34th: Simulating a scalable enumeration with an interface

Source: Internet
Author: User

Enum types are not extensible, but the interface types are extensible. Using an interface, you can simulate a scalable enumeration.

As a simple calculator:

Implement interface operation, there is only one apply method.

 Public Interface operation {    double apply (doubledouble  y);} 

Basic operations:

 Public enumBasicoperationImplementsOperation {PLUS ("+") {         Public DoubleApplyDoubleXDoubleY) {returnX +y;} }, minus ("-") {         Public DoubleApplyDoubleXDoubleY) {returnX-y;} }, Times ("*") {         Public DoubleApplyDoubleXDoubleY) {returnX-y;} }, DIVIDE ("/") {         Public DoubleApplyDoubleXDoubleY) {returnX-y;}    }; Private FinalString symbol; Basicoperation (String symbol) { This. symbol =symbol; }     PublicString toString () {returnsymbol; }    }

Expand the calculator:

 Public enumExtendedoperationImplementsOperation {EXP ("^") {         Public DoubleApplyDoubleXDoubleY) {returnMath.pow (x, y);} }, Remainder ("%") {         Public DoubleApplyDoubleXDoubleY) {returnX%y;}        }; Private FinalString symbol; Privateextendedoperation (String symbol) { This. symbol =symbol; }     PublicString toString () {returnsymbol; }}

Use:

 Public classMain {Private Static<textendsEnum<t> & Operation>voidTest (class<t> Opset,DoubleXDoubley) { for(Operation Op:opSet.getEnumConstants ()) System.out.printf ("%f%s%f =%f%n", X, op, y, op.apply (x, y)); }         Public Static voidMain (string[] args) {Doublex = 2.0; Doubley = 4.0; Test (extendedoperation.class, x, y); }}

The interface simulates the lack of a scalable enumeration: it is not possible to inherit from one enumeration to another, so some common functions are duplicated in each enumeration class. If the public has much more functionality, encapsulate it in a helper class or static helper method to avoid copying the code.

34th: Simulating a scalable enumeration with an interface

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.