Search code examples
javadesign-patternsstrategy-pattern

Strategy Design Pattern (with argument method) - JAVA


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


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