Skip to content

Instantly share code, notes, and snippets.

@gustavofonseca
Created May 30, 2011 18:22
Show Gist options
  • Save gustavofonseca/999251 to your computer and use it in GitHub Desktop.
Save gustavofonseca/999251 to your computer and use it in GitHub Desktop.
Chain if responsibility example in java(GoF design pattern)
abstract class Animal {
public Animal successor = null;
abstract public void processRequest(String request);
}
class Cat extends Animal {
public void processRequest(String request) {
Boolean isCat = request.contains("miau") ? true : false;
if(isCat){
System.out.println("handled by a Cat instance!");
} else if (successor != null){
successor.processRequest(request);
} else {
System.out.println("Cat does not have a successor =/");
}
}
}
class Dog extends Animal {
public void processRequest(String request) {
Boolean isDog = request.contains("auau") ? true : false;
if(isDog){
System.out.println("handled by a Dog instance!");
} else if (successor != null){
successor.processRequest(request);
} else {
System.out.println("Dog does not have a successor =/");
}
}
}
class Dispatcher {
Cat cat = new Cat();
Dog dog = new Dog();
public void handleForMe(String request) {
cat.successor = dog;
cat.processRequest(request);
}
}
class Run {
public static void main(String[] args) {
Dispatcher dispatcher = new Dispatcher();
dispatcher.handleForMe("the animal who says \"auau\"");
dispatcher.handleForMe("the animal who says \"miau\"");
dispatcher.handleForMe("the animal who says \"hakuna matata\"");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment