Singleton Pattern
1 posts in topic
Flat View  Flat View

Posted By:   kulbir_singh
Posted On:   Wednesday, February 21, 2007 04:12 AM

Hi Java Gurus,

im new to this group. Friends, i have one query regarding Singleton patterns.

what is the basic concept of singleton?
i know that only one instance of the class will be created through the static method and the constructor will be private. but the problem is we cant extends that singeton class.

i dont have any requirement to extend the singleton class, just for my knowledge im asking that is this the feature or drawback of singlton pattern?

Kulbir Singh

Re: Singleton Pattern

Posted By:   Robert_Lybarger  
Posted On:   Wednesday, February 21, 2007 11:05 PM

The constructor needn't be "private" ... it could be "protected" to allow subclassing. The main idea is that it just isn't "public". The static bits (the class reference and the initializer/accessor) would, however, need to be recreated in the subclass, as static elements don't inherit. (This being the case, the static class reference could be left private, as it doesn't really matter; leaving it as private is usually a faster clue for someone else reading the code than it also being static.) Consider:

public class SingletonBase {

private static SingletonBase instance = null;

protected int value;

protected SingletonBase() {
value = 42;

public static SingletonBase getInstance() {
if (instance==null) {
instance = new SingletonBase();
return instance;

public int getValue() {
return value;

public class SingletonSub extends SingletonBase {

private static SingletonSub instance = null;

protected SingletonSub() {

public static SingletonSub getInstance() {
if (instance==null) {
instance = new SingletonSub();
return instance;

/*test 'main' method*/
public static void main(String[] args) {
SingletonBase base = SingletonBase.getInstance();
SingletonSub sub = SingletonSub.getInstance();


That being said, I've never really needed to do this -- those classes I've wrapped a singleton pattern around could be marked 'final' for what I've used them for, and therefore I just use 'private' for those variables. Hopefully someone a little more versed in patterns theory could be a bit more informative as to whether a subclass on a 'singleton'ed class is a good idea, or whether some other pattern/concept can help out...?

About | Sitemap | Contact