dimanche 19 novembre 2017

Best design pattern to support valueOf() function of generic class

I have an interface Operations:

public interface Operations{

    Operations add(Operations op);

    Operations subtract(Operations op);
}

This interface should allow the user to choose how to do simple calculations. For example if the user just wants to use the data type Integer and its basic operations he can use the class MyInteger:

// 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);
    }
    (...)
}

In other classes there will take place calculations based on the functions of the interface Operations. But sometimes i need a static valueOf(int val) functions that returns an implementation of the corresponding class, like in this example:

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);
    }
}

So

Calculation<MyInteger> calc = new Calculation<MyInteger>(new MyInteger(1), new MyInteger(2));
Operations result = calc.sumPlusValue3();

In general i think i have to use a design pattern like Builder or a Factory to allow the user to specify which implementation he wants, like

Operations integerImpl = OperationsBuilder.create("Integer");

But also after studying those patterns, i could not find a clean way to get an implementation of the generic class D for value3 in the Calculation class.

Aucun commentaire:

Enregistrer un commentaire