FizzBuzz is a well known Exercise among programmers, but I wanted to add an aspect called "openClosed" principle (from SOLID)
FizzBuzz is a very simple programming task, used in software developer job interviews, to determine whether the job candidate can actually write code. It was invented by Imran Ghory, and popularized by Jeff Atwood. Here is a description of the task:
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
App for running an example
public class App{
public static void main(String[] args) {
FizzBuzz fizzBuzz = new FizzBuzz();
fizzBuzz.addHandler(new FizzHandler());
fizzBuzz.addHandler(new BuzzHandler());
fizzBuzz.print(100);
}
}
Handler
public interface Handler {
boolean matches(int number);
String getMessage();
}
FizzHandler an Handler
implementation
public class FizzHandler implements Handler {
@Override
public boolean matches(int number) {
return number % 3 == 0;
}
@Override
public String getMessage() {
return "Fizz";
}
}
BuzzHandler an Handler
implementation
public class BuzzHandler implements Handler {
@Override
public boolean matches(int number) {
return number % 5 == 0;
}
@Override
public String getMessage() {
return "Buzz";
}
}
FizzBuzz
public class FizzBuzz {
private List<Handler> handlers = new ArrayList<>();
public void print(int countDestination) {
IntStream.range(0,countDestination).forEach(this::printFizzBuzz);
}
private void printFizzBuzz(int i) {
List<Handler> matchingHandler = handlers.stream().filter(h -> h.matches(i)).toList();
String output = matchingHandler.isEmpty()?
Integer.toString(i):
matchingHandler.stream().map(Handler::getMessage).collect(Collectors.joining());
System.out.println(output);
}
public void addHandler(Handler handler) {
handlers.add(handler);
}
}
FractionHandler
\$\endgroup\$