Effective Java 34 Emulate extensible enums with interfaces
|
Advantage |
Disadvantage |
|
|
Enum types |
Clarity Safety Ease of maintenance. |
None extensibility |
|
Typesafe enum pattern(Interfaces to emulate extensible enums) |
Extensibility |
No good way to enumerate all of the elements of a base type and its extension. Extensibility would complicate many aspects of the design and implementation. Implementations cannot be inherited from one enum type to another. |
Scenario
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.
Compelling use case for extensible enumerated type -- Operation codes/ opcodes.
Usage
- Pass a single instance of an "extension enum" anywhere a "base enum" is expected.
/**
* Demo for "34 Emulate extensible enums with interfaces".
*/
package com.effectivejava.EnumAnnotations;
/**
* @author Kaibo
*
*/
public interface Operation {
double apply(double x, double y);
}
/**
* Demo for the "34 Emulate extensible enums with interfaces".
*/
package com.effectivejava.EnumAnnotations;
import java.util.HashMap;
import java.util.Map;
/**
* @author Kaibo
*
*/
public enum BaseOperation 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;
BaseOperation(String symbol) {
this.symbol = symbol;
}
@Override
public String toString() {
return symbol;
}
public abstract double apply(double x, double y);
// Implementing a fromString method on an enum type
private static final Map<String, BaseOperation> stringToEnum = new HashMap<String, BaseOperation>();
static { // Initialize map from constant name to enum constant
for (BaseOperation op : values())
stringToEnum.put(op.toString(), op);
}
// Returns BaseOperation for string, or null if string is invalid
public static BaseOperation fromString(String symbol) {
return stringToEnum.get(symbol);
}
}
- Pass in an entire extension enum type and use its elements in addition to or instead of those of the base type.
/**
* Demo for the "34 Emulate extensible enums with interfaces".
*/
package com.effectivejava.EnumAnnotations;
/**
* @author Kaibo
*
*/
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;
}
}
Note
- Passing the extended enums between methods.
- Bounded type token
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> opSet, double x, double y) {
for (Operation op : opSet.getEnumConstants())
System.out.printf("%f %s %f = %f%n", x, op, y, op.apply(x, y));
}
b. Passing with Collection<? Extends Operation>
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));
}
2. The logic to store and retrieve the symbol associated with an operation is 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.
Summary
While you cannot write an extensible enum type, you can emulate it by writing an interface to go with a basic enum type that implements the interface.
Effective Java 34 Emulate extensible enums with interfaces的更多相关文章
- Effective Java Index
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...
- 《Effective Java》读书笔记 - 6.枚举和注解
Chapter 6 Enums and Annotations Item 30: Use enums instead of int constants Enum类型无非也是个普通的class,所以你可 ...
- Effective Java 目录
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...
- 【Effective Java】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...
- Effective Java 第三版——34. 使用枚举类型替代整型常量
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java 第三版——38. 使用接口模拟可扩展的枚举
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java 第三版笔记(目录)
<Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将近8年的时 ...
- [Effective Java]第八章 通用程序设计
声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...
- Effective Java通俗理解(下)
Effective Java通俗理解(上) 第31条:用实例域代替序数 枚举类型有一个ordinal方法,它范围该常量的序数从0开始,不建议使用这个方法,因为这不能很好地对枚举进行维护,正确应该是利用 ...
随机推荐
- Activating Browser Modes with Doctype
原文地址:https://hsivonen.fi/doctype/ In order to deal both with content written according to Web standa ...
- C#动态属性(.NET Framework4.5支持)
获取方法: /* 使用方法: 1. 在web.config 的<configSections> 节点中添加 <section name="customConfigs&quo ...
- .NET 配置文件简单使用
当我们开发系统的时候要把一部分设置提取到外部的时候,那么就要用到.NET的配置文件了.比如我的框架中使用哪个IOC容器需要可以灵活的选择,那我就需要把IOC容器的设置提取到配置文件中去配置.实现有几种 ...
- ref和out 传递参数(C#)
1.参数传递默认都是传递栈空间里面存储的内容 2.如果添加了ref那么传递的都是栈空间地址,而不再是栈空间里面的内容 3.如果添加了out,那么传递的也是栈空间的地址 //写一个方法计算一个int类型 ...
- 【iOS】FMDB封装,查询自动mapping
sqlite几乎所有的App都会用到,但是系统自带的sqlite API是用C语言写的,非常不友好,用起来非常不便,通常我们使用第三方封装好的工具,例如:FMDB(https://github.com ...
- MySQL的字符集
MySQL的字符集支持(Character Set Support)有两个方面:字符集(Character set)和排序方式(Collation). 字符(Character)是指人类语言中最小的表 ...
- CountDownLatch,CyclicBarrier,Semaphore
CountDownLatch是倒数,doneSignal = new CountDownLatch(LATCH_SIZE);赋初值后,在主线程中等待doneSignal.await();其它线程中,每 ...
- java开发-技能要求-分词频度统计
描述: 一哥们离职找工作,最近聊了聊面试待遇要求一类的事情,有些感触. 在一个公司呆的时间长了,对市场上对开发的要求已经不那么敏感了,也不知道人家要求哪些技能.一个公司的业务是有限的,呆了2年,3年, ...
- 备份一张iPhone拍照写入exif中的orientation图片
- VM虚拟机忘记密码
关掉虚拟机. VM->Settings,选中Hard Disk,在右边出现了Utilities的一个下拉栏,OK,点击它选择Map,这时弹出一个"Map Virtual Disk&qu ...