Closed okhee closed 2 years ago
public interface Operation { double apply(double x, double y); }
public enum BasicOperation implements Operation { PLUS("+") { @Override public double apply(double x, double y) { return x + y; } }, MINUS("-") { @Override public double apply(double x, double y) { return x - y; } }, TIMES("*") { @Override public double apply(double x, double y) { return x * y; } }, DIVIDE("/") { @Override 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; } }
BasicOperation
Operation
public enum ExtendedOperation implements Operation { EXP("^") { @Override public double apply(double x, double y) { return Math.pow(x, y); } }, REMATINDER("%") { @Override 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; } }
ExtendedOperation
public class Page215Ex { public static void main(String[] args) { double x = Double.parseDouble("12"); double y = Double.parseDouble("34"); 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)); } } }
12.000000 ^ 34.000000 = 4922235242952026400000000000000000000.000000 12.000000 % 34.000000 = 12.000000 Process finished with exit code 0
<T extends Enum<T> & Operation> Class<T>
Collection<? extends Operation>
public class SecondEx { public static void main(String[] args) { double x = Double.parseDouble("12"); double y = Double.parseDouble("34"); test(Arrays.asList(ExtendedOperation.values()), x, y); } private static <T extends Enum<T> & Operation> 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)); } } }
java.nio.file.LinkOption
CopyOption
OpenOption
확장할 수 있는 열거 타입이 필요하면 인터페이스를 사용하라
BasicOperation
은 확장할 수 없지만 인터페이스인Operation
은 확장 가능Operation
을 구현한 다른 열거 타입을 대체해서 사용 가능Operation
인터페이스를 사용하도록 작성되어 있기만 하면BasicOperation
,ExtendedOperation
어느 것이든 사용 가능<T extends Enum<T> & Operation> Class<T>
)은 복잡...Collection<? extends Operation>
java.nio.file.LinkOption
열거 타입CopyOption
,OpenOption
인터페이스를 구현핵심 정리