Skip to content

Instantly share code, notes, and snippets.

@ajspadial
Last active August 29, 2015 14:28
Show Gist options
  • Save ajspadial/d7af3b29e24edcce1439 to your computer and use it in GitHub Desktop.
Save ajspadial/d7af3b29e24edcce1439 to your computer and use it in GitHub Desktop.
Java closure vs 1-method malefic class
// # Common declarartion
interface Displayable {
void draw();
}
// # Closure style
Function<Void, Void> blinker;
blinker = getBlinker(funnyText, 3);
Function<Void, Void> getBlinker(Displayable display, float FPS) {
float time0 = millis();
boolean blink = false;
return () => {
if (millis() > time0 + 1000 / FPS) {
blink = !blink;
time0 = millis();
}
if (!blink) {
display.draw();
}
}
}
blinker.apply();
// # 2. Evil 1-method class
// Be careful here, yor eyes may bleed
Blinker blinker = new Blinker(funnyText, 3);
class Blinker { //[optional] implement Displayable
private float time0;
private boolean blink;
private Displayable display;
private float FPS;
Blinker(Displayable display, float FPS) {
time0 = millis();
blink = false;
this.FPS = FPS;
this.display = display;
}
void draw() {
if (millis() > time0 + 1000 / FPS) {
blink = !blink;
time0 = millis();
}
if (!blink) {
display.draw();
}
}
}
blinker.draw();
function getBlinker($display, $FPS) {
$time0 = millis(); // timestamp in milliseconds
$blink = false;
return function() {
if (millis() > $time0 + 1000 / $FPS) {
$blink = !$blink;
$time0 = millis();
}
if (!$blink) {
display->draw();
}
}
}
$blinker = getBlinker($funnyText, 3);
call_user_func($blinker);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment