Skip to content

Instantly share code, notes, and snippets.

@yoshiori
Created April 25, 2011 04:35
Show Gist options
  • Save yoshiori/940163 to your computer and use it in GitHub Desktop.
Save yoshiori/940163 to your computer and use it in GitHub Desktop.
Chain of Responsibility で fizzbuzz
/**
*
*/
package org.yoshiori.cor;
/**
* @author yoshiori
*
*/
public class CoR {
/**
* @param args
*/
public static void main(String[] args) {
AbstractHandler handler = new Fizz();
handler.setNext(new Buzz())
.setNext(new FizzBuzz())
.setNext(new Default());
for(int i =1 ; i < 100 ; i++ ){
handler.fizzbuzz(i);
}
}
static abstract class AbstractHandler{
AbstractHandler next;
public void fizzbuzz(int i) {
if(!execute(i) && next != null){
next.fizzbuzz(i);
}
}
public AbstractHandler setNext(AbstractHandler next){
this.next = next;
return next;
}
abstract protected boolean execute(int i);
}
static class Fizz extends AbstractHandler{
@Override
protected boolean execute(int i) {
if(i % 3 == 0 && i % 5 != 0){
System.out.println("fizz");
return true;
}
return false;
}
}
static class Buzz extends AbstractHandler{
@Override
protected boolean execute(int i) {
if(i % 5 == 0 && i % 3 != 0){
System.out.println("buzz");
return true;
}
return false;
}
}
static class FizzBuzz extends AbstractHandler{
@Override
protected boolean execute(int i) {
if(i % 3 == 0 && i % 5 == 0){
System.out.println("fizzbuzz");
return true;
}
return false;
}
}
static class Default extends AbstractHandler{
@Override
protected boolean execute(int i) {
if(i % 3 != 0 && i % 5 != 0){
System.out.println(i);
return true;
}
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment