1 package com.twoslow.cha6;
2
3 public interface OperationInterface {
4
5 double apply(double x , double y) ;
6 }
1 package com.twoslow.cha6;
2
3 public enum BaseOperation implements OperationInterface{
4
5 PLUS("+"){
6 public double apply(double x , double y ) {return x + y ;}
7 },
8 MINUS("-"){
9 public double apply(double x , double y ) {return x - y ;}
10 },
11 TIMES("*"){
12 public double apply(double x , double y ) {return x * y ;}
13 },
14 DIVIDE("/"){
15 public double apply(double x , double y ) {return x / y ;}
16 } ;
17
18 private final String symbol ;
19
20 BaseOperation(String symbol) {
21 this.symbol = symbol ;
22 }
23 }
1 package com.twoslow.cha6;
2
3 public enum ExtendedOperation implements OperationInterface{
4
5 EXP("^") {
6 public double apply(double x, double y){return Math.pow(x, y) ;};
7 } ,
8
9 REMAINDER("%") {
10 public double apply(double x , double y ) {return x % y ;} ;
11 } ;
12
13
14 private final String symbol ;
15
16 ExtendedOperation(String symbol) {
17 this.symbol = symbol ;
18 }
19 }
1 package com.twoslow.cha6;
2
3 import java.util.Arrays;
4 import java.util.Collection;
5
6 public class MainTest {
7
8 public static void main(String[] args) {
9 // test(ExtendedOperation.class , 3,2) ;
10
11 test2(Arrays.asList(BaseOperation.values()),3,2) ;
12 }
13
14 //泛型声明确保对象既表示枚举又表示Operation的子类型
15 private static <T extends Enum<T> & OperationInterface> void test(Class<T> opSet , double x , double y ) {
16 for(OperationInterface op : opSet.getEnumConstants()) {
17 System.out.println(op.apply(x, y));
18 }
19 }
20
21 private static void test2(Collection<? extends OperationInterface> opSet , double x , double y ) {
22 for(OperationInterface op : opSet) {
23 System.out.println(op.apply(x, y));
24 }
25 }
26 }