1) : factory
:
private final D value3 = D.valueOf(4);
value3 , factory.
valueOf() ( ) .
factory Calculation, value3.
, :
private final D value3 = D.valueOf(4);
public Calculation(D value1, D value2){
this.value1 =value1;
this.value2 = value2;
}
:
private final D value3;
public Calculation(D value1, D value2, FactoryD factoryD){
this.value1 =value1;
this.value2 = value2;
this.value3 = factoryD.create(4);
}
Function factory:
private final D value3;
public Calculation(D value1, D value2, IntFunction<D> factoryD){
this.value1 =value1;
this.value2 = value2;
this.value3 = factoryD.apply(4);
}
:
Calculation<MyInteger> calc = new Calculation<>(new MyInteger(1), new MyInteger(2), MyInteger::new );
Operations result = calc.sumPlusValue3();
Operations -.
2) Operations .
, Operations , :
public interface Operations{
Operations add(Operations op);
Operations subtract(Operations op);
}
:
public interface Operations<T> {
Operations<T> add(Operations<T> op);
Operations<T> subtract(Operations<T> op);
T getValue();
}
MyInteger :
public final class MyInteger implements Operations<Integer> {
private final int delegate;
public MyInteger(int i) {
delegate = i;
}
@Override
public Operations<Integer> add(Operations<Integer> other) {
return new MyInteger(delegate + other.getValue());
}
@Override
public Operations<Integer> subtract(Operations<Integer> other) {
return new MyInteger(delegate - other.getValue());
}
@Override
public Integer getValue() {
return delegate;
}
}
Calculation : Operations Operations :
public class Calculation<C, D extends Operations<C>> {
private final D value1, value2;
private final D value3;
public Calculation(D value1, D value2, IntFunction<D> factoryD){
this.value1 =value1;
this.value2 = value2;
this.value3 = factoryD.apply(4);
}
public Operations<C> sumPlusValue3(){
return value1.add(value2).add(value3);
}
}
:
Calculation<Integer, MyInteger> calc = new Calculation<>(new MyInteger(1), new MyInteger(2), MyInteger::new );
Operations<Integer> result = calc.sumPlusValue3();
System.out.println(result.getValue());
:
7