Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

implementing singleton pattern in an interface

 
mangesh lele
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
mangesh lele
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic