I'm currently working on a project and I've reached a roadblock, and I need some perspective on how to design this
To give an analogy, I'll pretend this has to do with dogs - they have similar traits but each differ in their own way
Code
public class Doberman {
functionA();
functionB();
functionC();
}
Code
public class Chihuahua {
functionA();
functionB();
functionC();
}
Now I have a class called Dog - what I would like to do , although I can't, is design it so that Dog will extend Doberman iff some condition is met, and it will extend Chihuahua if the condition is not met.
The problem is I HAVE to use the Dog class because it is plugged in and Im not supposed to alter the code behind that - so in other words I can't put conditions outside of the dog class.
So ideally Dog would act as a layer between the plugin and the 2 types of dogs. If a condition is met, start calling the doberman code. Otherwise, call the chihuahua code
Code
public class Dog {
if (condition == true)
call functionA() from the doberman
else
call functionA() from the Chihuahua
}
But since I can't extend 2 classes or extend based on a condition, my idea is this. I think it works but I'm not sure it's the best solution since I'm inlining a conditionFunction() call in several functions
Code
public class [strikethrough]Dog[/strikethrough] Chihuahua extends Doberman{
boolean Conditionfunction(){
//return true if Doberman
}
functionA(){
if (conditionFunction()) super.functionA(); //Use the doberman code
else
//continue functions code as a chihuahua
}
//functionB() <--doesnt need to call it here since doberman is abstract and both chihuahua and doberman have the same trait here (eliminates redundancy)
functionC(){
if (conditionFunction()) super.functionC(); //Use the doberman code
else
//continue functions code as a chihuahua
}
Code
public abstract class Doberman{
functionA(){
//coded as a Doberman (but also works for chihuahua
}
functionB(){
//coded as a Doberman (doesnt work for chihuahua)
}
functionC(){
//coded as a Doberman (but also works for chihuahua
}
Since the chihuahua (formerly "dog") class is plugged in, its getting its function calls elsewhere. So it will try to call functionB() in chihuahua, but since chihuahua doesnt have it, it will grab from Doberman
Thanks
This post was edited by oOn on Jun 4 2014 12:34am