// 타입 안전 열거 패턴의 예시
public class TypeSafeEnum {
private final String type;
private TypeSafeEnum(String type) {
this.type = type;
}
public String toString() {
return type;
}
public static final TypeSafeEnum typeSafeEnum1 = new TypeSafeEnum("type1");
public static final TypeSafeEnum typeSafeEnum2 = new TypeSafeEnum("type2");
}
// 연산 코드용 인터페이스 정의
public interface Operation {
double apply(double x, double y);
}
public enum BasicOperation 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;
BasicOperation(String symbol) {
this.symbol = symbol;
}
@Override public String toString() {
return symbol;
}
}
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;
}
}
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> opEnumType, double x, double y) {
for (Operation op : opEnumType.getEnumConstants())
System.out.printf("%f %s %f = %f%n",
x, op, y, op.apply(x, y));
}
- 해당 class 리터럴은 한정적 타입 토큰 역할을 한다.
<T extends Enum<T> & Operation>
: Class 객체가 열거 타입인 동시에 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));
}
- EX) java.nio.file.LinkOption 열거 타입은 CopyOption, OpenOption 인터페이스를 구현했다.
Reference: