第六章:枚举和注解。ITEM34:用接口模拟可伸缩的枚举。

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 }

 

转载于:https://my.oschina.net/u/726229/blog/310086

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值