Skip to content

Instantly share code, notes, and snippets.

@zer0tonin
Created October 1, 2017 18:13
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 zer0tonin/3832f5d716fff189bc6124e100ee6874 to your computer and use it in GitHub Desktop.
Save zer0tonin/3832f5d716fff189bc6124e100ee6874 to your computer and use it in GitHub Desktop.
An overengineered FizzBuzz
public class Counter {
private int count = 1;
private int max;
public Counter(int max) {
this.max = max;
}
public int getCount() {
return count;
}
public synchronized void incrementCount() {
count++;
}
public boolean hasReachedMax() {
return count > max;
}
}
public class FizzBuzz {
public static void main(String[] args) {
Counter counter = new Counter(30);
Modulo moduloThree = (number) -> (number % 3 == 0) && (number % 5 != 0);
PrinterThread fizzThread = new PrinterThread(counter, "fizzThread", moduloThree, "Fizz");
Modulo moduloFive = (number) -> (number % 5 == 0) && (number % 3 != 0);
PrinterThread buzzThread = new PrinterThread(counter, "buzzThread", moduloFive, "Buzz");
Modulo moduloAll = (number) -> (number % 5 == 0) && (number % 3 == 0);
PrinterThread fizzBuzzThread = new PrinterThread(counter, "fizzBuzzThread", moduloAll, "FizzBuzz");
Modulo moduloNone = (number) -> (number % 5 != 0) && (number % 3 != 0);
PrinterThread numberThread = new PrinterThread(counter, "numberThread", moduloNone);
fizzThread.start();
buzzThread.start();
fizzBuzzThread.start();
numberThread.start();
}
}
@FunctionalInterface
public interface Modulo {
public boolean check(int number);
}
public class PrinterThread implements Runnable {
protected Thread thread;
protected String threadName;
protected Counter counter;
protected Modulo modulo;
protected String display;
public PrinterThread(Counter counter, String threadName, Modulo modulo, String display) {
super();
this.counter = counter;
this.threadName = threadName;
this.modulo = modulo;
this.display = display;
}
public PrinterThread(Counter counter, String threadName, Modulo modulo) {
super();
this.counter = counter;
this.threadName = threadName;
this.modulo = modulo;
}
@Override
public void run() {
while(!counter.hasReachedMax()) {
if(modulo.check(counter.getCount())) {
if (this.display == null) {
System.out.println(counter.getCount());
} else {
System.out.println(display);
}
counter.incrementCount();
}
}
}
public void start() {
if (thread == null) {
thread = new Thread(this, threadName);
thread.start();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment