File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes implementing singleton pattern in an interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "implementing singleton pattern in an interface" Watch "implementing singleton pattern in an interface" New topic

implementing singleton pattern in an interface

mangesh lele

Joined: Jan 17, 2003
Posts: 18
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
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
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
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
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
mangesh lele

Joined: Jan 17, 2003
Posts: 18
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.
I agree. Here's the link:
subject: implementing singleton pattern in an interface
It's not a secret anymore!