码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-08-27 12:56:07      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   java   io   for   ar   div   

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 }

 

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

标签:style   blog   color   os   java   io   for   ar   div   

原文地址:http://www.cnblogs.com/twoslow/p/3939164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!