effect java 学习摘要(5) - 枚举和注解

xiaoxiao2021-02-28  92

enum枚举类型代替int常量

枚举enum示例 :

public enum Apple{ FUJI(1), PIPPIN(2), GRANNY_SMITH(3); private int category; Apple(int category) { this.category = category; } } public enum Orange{NAVEL, TEMPLE, BLOOD}

枚举本质上是int值

枚举类型为类型安全的枚举模式

策略枚举 : 利用抽象方法, 避免switch过于复杂,冗余

public enum PayrollDay { MONDAY(PayType.WEEKDAY), TUESDAY(PayType.WEEKDAY), WEDNESDAY(PayType.WEEKDAY), THURSDAY(PayType.WEEKDAY), FRIDAY(PayType.WEEKDAY), SATURDAY(PayType.WEEKEND), SUNDAY(PayType.WEEKEND); private final PayType payType; PayrollDay(PayType payType) { this.payType = payType; } double pay(double hoursWorked, double payRate) { return payType.pay(hoursWorked, payRate); } private enum PayType { WEEKDAY { @Override double overtimePay(double hours, double payRate) { return hours <= HOURS_PER_SHIT ? 0 : (hours - HOURS_PER_SHIT) * payRate / 2; } }, WEEKEND { @Override double overtimePay(double hours, double payRate) { return hours * payRate / 2; } }; private static final int HOURS_PER_SHIT = 8; abstract double overtimePay(double hours, double payRate); double pay(double hoursWorked, double payRate) { double basePay = hoursWorked + payRate; return basePay + overtimePay(hoursWorked, payRate); } } }

用实例代替序数

``` public enum Apple{ FUJI(1), PIPPIN(2), GRANNY_SMITH(3); private int category; Apple(int category) { this.category = category; } } ```

用EnumSet替代位域

``` public static class Text { public static final int STYLE_BOLD = 1 << 0; public static final int STYLE_ITALIC = 1 << 1; public enum Style {BOLD ,ITALIC;} } ```

use an EnumMap to associate data with an enum

``` public class Herb { public enum Type {ANNUAL, PERENNIAL, BIENNIAL} final String name; final Type type; public Herb(String name, Type type) { this.name = name; this.type = type; } @Override public String toString() { return name; } } public void associate() { Map<Herb.Type , Set<Herb>> hrebsByType = new EnumMap<Herb.Type, Set<Herb>>(Herb.Type.class); for (Herb.Type t : Herb.Type.values()) { hrebsByType.put(t, new HashSet<Herb>()); } for (Herb h : garden) { hrebsByType.get(h.type).add(h); } } ```

用接口模拟可伸缩的枚举

虽然无法编写可扩展的枚举类型, 却可以通过编写接口以及实现该接口的基础枚举类型

注解

通过Retention和Target注解进行注解, 被称为元注解(meta-annotation)

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Test { }
转载请注明原文地址: https://www.6miu.com/read-67674.html

最新回复(0)