i have an interface which is to be implemented by several classes. all the classes implementing this interface are supposed to be singleton classes, or else they cant implement the interface. i am making the classes singleton by the usual approach of having a static getInstance() method which calls the private constructor if the static member instance of the class is null, else it returns the same instance. i want to make it mandatory for any class implementing the interface to have this getInstance method. the problem i'm facing is that i can't declare this getInstance method in the interface since it is static. apparently the 'static' modifier is not allowed in interface method declaration. is there a way to specify singleton pattern implementation in an interface?
Peter den Haan
Joined: Apr 20, 2000
No. What you can do, however, is use factory classes and define an interface for the factory. The factory can implement whatever creational pattern is appropriate. The factory interface wouldn't force this pattern to be the Singleton pattern as such, but IMHO this is entirely right and proper -- the creational design of your objects is an implementation concern rather than an interface concern. Client code would just instantiate a FooBarFactory and call create() on it to create a FooBar object; the FooBarFactory could use straight creation using new(), a Singleton, an instance pool, or something else altogether. Client code shouldn't know and shouldn't care. - Peter
Joined: Jan 30, 2000
You can also say in the javadoc comments for the interface (which becomes the API documentation) "this is a singleton - there can be only one instance of a class implementing this interface." This means that implementing classes are, well, morally obligated to implement using a singleton. But unfortunately there's no way to get the compiler to enforce this. Of course, Peter's answer is probably more useful to you...
"I'm not back." - Bill Harding, Twister
Joined: Jan 17, 2003
thanx a lot u guys! i kinda guessed it would have to use some sorta abstract class but was hoping it wud be possible in the existing class structure.