Question

I'm writing an algorithm which works on a bit serie and do some operations such as shift, AND with it. I wanted to test the algorithm with two different data structure : MutableBigInteger and BitString ( javabdd ), so I thought I'll try to come up with some smart design pattern (since i dont do that a lot) , and I found the strategy design pattern pretty interesting. The only thing that bothers me is that for the function AND, it needs the same type to be computed. I explain with some code :

Theses are my two different class :

public class MutableBigInteger {

public void shift();
public void and(MutableBigInteger b2){
    // ...
}
}


public class BitString {

public void shift();
public void and(BitString b2){
    // ...
     }
}

I want to make a design so at the creation on my class which does the algorithm I just choose between those classes. The algorithm looks like :

while( ... ) {
    bittrain.shift();
    bittrain.and(bittrain2);
}

The question for me is how to achieve that with the function AND, since each my own class waits the same class in argument. I thought I'd like this :

public interface BitTrain {

public void shift();
public void and(BitTrain b2);

}

and extend my two classes with this interface, but it doesn't really help me because, in MutableBigInteger and BitString I will have to do a cast, I don't really want that (because of speed).

Hoping I had explained it well enough, I wish you a good day !

Nico

Was it helpful?

Solution

Don't think this is the cleanest way, but you could use generics:

public interface BitTrain<T extends BitTrain<?>> {
    public void shift();
    public void and(T b2);
}

And then implement the interface like:

public class MutableBigInteger implements BitTrain<MutableBigInteger> {
    public void shift();
    public void and(MutableBigInteger b2){
        // ...
    }
}

OTHER TIPS

This sounds like premature optimization to me. Are you sure that the checkcast bytecode would affect your overall performance that much? I think this falls under "HotSpot can do that".

I did not understand the question fully , but are you by any chance thinking about the template pattern

public class MyBitOperation<T> {

T b1;

public MyBitOperation(T b) {
    b1= b;
}
public void shift(){

//TODO: DO something
}
public void and(T b2){

    //Do somehting else
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top