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 StrategyForObject**N**
class, but not to change the Conext
class.
In Strategy pattern we have to specify the Strategy 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?
Edit:
The IObject
can not be changed in order to add additional methods.
I must separate logic from data,so it is not desirable to add implementation of the logic in Object1
class for example.