Skip to content

Instantly share code, notes, and snippets.

@nikreiman
Created August 17, 2011 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikreiman/1151255 to your computer and use it in GitHub Desktop.
Save nikreiman/1151255 to your computer and use it in GitHub Desktop.
Java interface abuse
// 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();
}
}
}
// 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