를 구현하는 일반적인 클래스의 정적 기능을 지원합니다. 인터페이스 Operations
의 기능에 따라 위치 계산이 걸릴 것최고의 디자인 패턴은 내가 인터페이스 <code>Operations</code>이 인터페이스
// simple implementation without type check etc..
public final class MyInteger implements Operations{
private final int delegate;
public MyInteger(int i){
delegate = i;
}
@Override
Operations add(Operations other){
return new MyInteger(delegate + ((MyInteger) other).delegate);
}
@Override
Operations subtract(Operations other){
return new MyInteger(delegate - ((MyInteger) other).delegate);
}
(...)
}
다른 클래스에서 예를 들어 사용자는 단지 그가 클래스 MyInteger
를 사용할 수있는 데이터 유형 Integer
와 기본 조작을 사용하고자합니다.
public class Calculation<D extends Operations> {
private final D value1, value2;
private final D value3 = D.valueOf(4); // cannot implement this in interface
public Calculation(D value1, D value2){
this.value1 =value1;
this.value2 = value2;
}
public D sumPlusValue3(){
return value1.plus(value2).plus(value3);
}
}
그래서
Calculation<MyInteger> calc = new Calculation<MyInteger>(new MyInteger(1), new MyInteger(2));
Operations result = calc.sumPlusValue3();
:하지만 가끔은 내가이 예에서와 같이, 그래서 주어진 문자열, 더블, INT에 해당하는 클래스의 구현을 반환하고 valueOf(val)
기능과 같은 정적 컨텍스트를 필요 내가 생각 일반적으로 내가
Operations integerImpl = OperationsBuilder.create("Integer");
처럼 사용자가 자신이 원하는 어떤 구현 지정할 수 있도록
Builder 또는
Factory 같은 디자인 패턴을 사용해야합니다
그러나 이러한 패턴을 연구 한 후에도 클래스에 value3
에 대한 일반 클래스 D
의 구현을 얻는 명확한 방법을 찾을 수 없습니다.
EDIT 1은 :
나는 질문을 편집하고 내 문제에 대한 최선의 해결책이기 때문에 @Stefan HAUSTEIN에서 답을 표시했다. 그러나 @davidxxx의 답은 초기 질문과 관련하여 좋은 대답이기도합니다 - 을 나타내는 방법은valueOf(int val)
입니다. Calculation
당신이 항상 근처 어쨌든 D
의 인스턴스가있는 경우 기술적으로는 해당 값을 필요로하지 않지만
'int'를'double'에 추가하고 싶습니다. 가능합니까?'Operation' –
Andrew
아니요, 가능하지 않아야합니다. 즉, 모든 운영 구현이 동일한 인스턴스에 속해 있는지 확인해야합니다. Calculations 클래스에서 이는 generic 매개 변수 때문에 충족 되었습니까? – team17