This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton implementation Question

 
Susan
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

typically a singleton implementation is like:

public final class Singleton {
private static Singleton single = new Singleton();

private Singleton() {}

public static Singleton getInstance() {
return single;
}

public void doSomethingMethod() {
// do something here
}
}


Another implementation could be:

public abstact class Singleton {

public static void doSomethingMethod() {
// do something here
}
}

I'm looking for the reasons why the first implementation is better than the second implementation?

thanks!

Susan
 
manuel aldana
Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well the second code is no Singleton.

1)it is abstract -> no instantiation possible
2)even if it was not abstract, there could be more than one instance in your JVM, so it couldn't be a singleton.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first implementation - the actual Singleton pattern - is more flexible:

- the getInstance method could return an instance of a subclass, and

- you can pass the object around, so that not all clients need to know it's a singleton.

And there is an even more flexible pattern - the Just Create One pattern.
 
Sachin Dimble
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could anybody explain why we required singleton class at all???(some live project ex. expected).


Thanx.
Sachin!!!
 
Vishnu Prakash
Ranch Hand
Posts: 1026
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Could anybody explain why we required singleton class at all???


Marking your constructor private will prevent your clients from instantiating you class directly. If suppose they want to access your class instance methods they need an instance of your class. So how do they get an instance of your class?

If you look at the first example provided Susan Oso, you can understand why Singleton is needed?
 
Kamesh Loganathan
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generally we use the singleton design pattern for factory classes, manager classes and classes for which we want only once instance in the whole application. It generally comes in very handy in Java swing programming.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic