Created
May 30, 2011 18:22
-
-
Save gustavofonseca/999251 to your computer and use it in GitHub Desktop.
Chain if responsibility example in java(GoF design pattern)
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
abstract class Animal { | |
public Animal successor = null; | |
abstract public void processRequest(String request); | |
} |
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
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 =/"); | |
} | |
} | |
} |
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
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 =/"); | |
} | |
} | |
} |
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
class Dispatcher { | |
Cat cat = new Cat(); | |
Dog dog = new Dog(); | |
public void handleForMe(String request) { | |
cat.successor = dog; | |
cat.processRequest(request); | |
} | |
} |
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
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