13
I would like to force some of my classes to be implemented in Singleton, but I came across the following situation.
interface ICharacterSingleton{
static Characters getInstancia();
}
public static class Zero extends Characters implements ICharacterSingleton {
private static Characters Instancia = null;
private Zero(){
Layout.add(" 111 ");
Layout.add(" 1 1 ");
Layout.add(" 1 1 ");
Layout.add(" 1 1 ");
Layout.add(" 1 1 ");
Layout.add(" 1 1 ");
Layout.add(" 1 1 ");
Layout.add(" 111 ");
}
public static Characters getInstancia() {
if(Instancia == null)
Instancia = new Zero();
return Instancia;
}
}
Can’t I define a static method for an interface? There is another way out of this situation?
It is good to note that - in Java 8 at least - you can yes have static methods on interfaces. However, you cannot use them to implement a Singleton, as well explained in the responses. Other languages (such as Python) differentiate between Static methods and class methods - the latter considering inheritance - but still it is not possible to require a derived class to give its own implementation of a class method. As Math said: "it is not possible to require by contract that a class be Singleton".
– mgibsonbr
P.S. If it weren’t for the multiple inheritance problem, you could create a base class that keeps a record of the created instances - through a
Map
withthis.getClass()
as key - and throws an exception if more than one instance of the same class is created. Any class you inherit from it would then in fact an Singleton. This base class could even have a utility method to recover the instance - serving as a factory for these objects, and centralizing their creation and access in a standardized way. I can post this as an answer if you like, but it still doesn’t apply to the use of interfaces.– mgibsonbr
@utluiz I liked the idea of Singletonfactory However I will have several class inheriting from "Characters" and all of them following the same concept generating a character map forming the number in ascii, in the example above I have the class Zero, I will have One, Two and so will all inherit Characters in the case of Singletonfactory I would have to have an object factory for each class as I would manage all these instances?
– Tuyoshi Vinicius