samedi 16 avril 2016

Choose implementation based on the type of the Object in Java

I have one parent type

public class IObject{}

and can have a lot of sub-classes(even new ones in the future)

public class Object1 extends IObject{}
public class Object2 extends IObject{}
public class Object3 extends IObject{}
...
public class ObjectN extends IObject{}

Then based on the type of these objects I have to do different operations.

public class StrategyForObject1(){void do{}}
public class StrategyForObject2(){void do{}}
public class StrategyForObject3(){void do{}}
...
 public class StrategyForObjectN(){void do{}}

So I want from my Context class:

public Conext{
IObject o;

public void setObject(IObject o){
this.o= o;
}

void logic(){
if(o instanceOf Object1){
new StrategyForObject1().do();
}
if(o instanceOf Object2){
new StrategyForObject2().do();
}
if(o instanceOf Object3){
new StrategyForObject3().do();
}
...
 if(o instanceOf ObjectN){
new StrategyForObjectN().do();
}
}
}

So based on the type to execute different algorithms, but I want to be extensible like in Strategy pattern if I need to add new sub-class of IObject just to add new StrategyForObjectN class, but not to change the Conext class. In stretegy pattern we have to specify the Stretegy but here we have to do the opposite to choose the strategy based on the type of the object. How to do that in Java in the best way?

Aucun commentaire:

Enregistrer un commentaire