I've created a singleton by means of an interface. I don't want to make a thing with getInstance()
etc because I don't care about inheritance, and it's redundant and non-declarative.
Are there downsides of doing it this way? Any redundancy I can remove? Is there a cleaner/more consise way to do this? I like doing it this way because methods are first class because I can pass them to map etc (e.g: map(Dog.sleep, someListOfNumbers)
) and it supports currying if you have functions like F<Pair<X,Pair<Y,Z>>>
.
Note the F
interface is declared elsewhere, I just inlined it here to have less files.
package a;
import static a.Dog.State.*;
public interface Dog {
interface F<X,Y> {
Y f(X x);
}
static final class State {
protected static boolean dead;
protected static String name = "leo";
protected static Integer age = 0;
}
F<Void,String> getName = new F<Void,String>() {
public String f(Void _) {
return name;
}
};
F<Void,Void> die = new F<Void,Void>() {
public Void f(Void _) {
System.out.println("X_X");
dead = true;
return null;
}
};
F<Void,Void> woof = new F<Void,Void>() {
public Void f(Void _) {
if (dead)
throw new IllegalStateException("cannot woof when dead");
System.out.println("woof");
return null;
}
};
F<Integer,Void> sleep = new F<Integer,Void>() {
public Void f(Integer years) {
if (dead)
throw new IllegalStateException("cannot sleep when dead");
age += years;
return null;
}
};
F<Void,Integer> getAge = new F<Void,Integer>() {
public Integer f(Void _) {
return age;
}
};
}
A test:
import a.Dog;
class Main {
public static void main(String[] args) {
System.out.println(
"The dog's name is " + Dog.getName.f(null) +
" and is " + Dog.getAge.f(null) + " years old"
);
Dog.sleep.f(2);
System.out.println(
"The dog's name is " + Dog.getName.f(null) +
" and is " + Dog.getAge.f(null) + " years old"
);
Dog.woof.f(null);
Dog.die.f(null);
Dog.woof.f(null);
}
}