Created
August 17, 2011 10:11
-
-
Save nikreiman/1151255 to your computer and use it in GitHub Desktop.
Java interface abuse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Fun trick I've been playing with to replace abstract classes with empty java interfaces. | |
public class BaseClass { | |
// stuff ... | |
} | |
public class PurpleClass extends BaseClass implements Controller.IsPurple { | |
// methods ... | |
} | |
public class OrangeClass extends BaseClass { | |
// methods ... | |
} | |
public class Controller { | |
public interface IsPurple {} | |
private BaseClass myClass; | |
public Controller(BaseClass baseClass) { | |
this.myClass = baseClass; | |
} | |
public void timeToDoSomething() { | |
if(this.myClass instanceof IsPurple) { | |
doSpecialThingHere(); | |
} | |
else { | |
doNotSoSpecialThingHere(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// More conventional, but more verbose approach to the same thing. Also, this approach means that | |
// the controller needs to know about the implementation details of BaseClass. | |
public abstract class BaseClass { | |
public abstract boolean isPurple(); | |
} | |
public class PurpleClass extends BaseClass { | |
public boolean isPurple() { | |
return true; | |
} | |
} | |
public class OrangeClass extends BaseClass { | |
public boolean isPurple() { | |
return false; | |
} | |
} | |
public class Controller { | |
private BaseClass myClass; | |
public Controller(BaseClass baseClass) { | |
this.myClass = baseClass; | |
} | |
public void timeToDoSomething() { | |
if(this.myClass.isPurple()) { | |
doSpecialThingHere(); | |
} | |
else { | |
doNotSoSpecialThingHere(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment