• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

singleton objects?

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Could someone explain what a Singleton object is, its uses and pecularities if any.
thanks in anticiption of reply.
 
Ranch Hand
Posts: 396
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Rajendra,
Singleton class is a class whose only one object can be created at a time.
To achieve this one method is that we make it's constructor private and provide a static method that returns it's instance. here is a code.

e.g. Runtime is a Singleton class in Java Library.
run the above code hope u'll understand the concept
regards
Deekasha
 
Rajendra Deshpande
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Deekasha,
Thanks for the reply. However, thats too much of a code for a novice like me. Could you be kind to explain the purpose of a 'private constructor'.
thanks,
Rajendra.
 
Sheriff
Posts: 7001
6
Eclipse IDE Python C++ Debian Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A singleton is an object of which there may only ever be a single instance. (*)
You can make your own class act like a singleton, simply by only creating a single instance. But this relies on every programmer who uses your code knowing that there is only supposed to be one instance of the class, which is dangerous. A better solution is to write the class in a way which prevents a casual programmer from creating more than one instance. This is where the Singleton pattern and its associated Java idioms help you.
Lets start with a simple class:

The most obvious way for a programmer to try to create an instance of a class is to call its constructor, so we need to prevent this. If we just fail to provide a constructor, Java assumes that there is a "default constructor" taking no arguments which just creates an instance of the class; not what we need! The Java "trick" for this is to have a constructor, but make it private so no other classes may call it.

Now that we have no constructor, we need to make a way for people to create a single instance of the class. Typically this is done by provding a static method which creates an instance, but will create only one. If it is called again, it just returns the same instance that it created the first time.

Now the code is almost complete. The last thing to remember is that Java is a multi-threaded language in which many things can be happening "at once". If two threads were to call getInstance at the same time, then our class might occasionally create two instances, which would be wrong and very hard to test. So we make use of Java's built-in synchronization mechanism to make sure that only one thread can call getInstance at any one time.
So the final singleton class looks like:

I hope this helps.

(*) The Singleton pattern actually allows for a specified number of instances, but singletons are harly ever used for any number other than one.
 
Rajendra Deshpande
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Frank Carver,
Thanks a lot. There cannot be a more clear and insightful explanation. You have been a great help.
-rajendra.
 
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Great Post Frank. Really explained it great.
Bill
 
tumbleweed and gunslinger
Posts: 192
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a question about this subject...
Currently, we have an application were we have DAO objects where the methods are static and Eclipse/PMD is complaining about using a singlton.
Our current usage is simple:

From your description of a singleton, as I understand, we would have to change the code to use the .getInstance() method such as:

If so, this would really suck having to go through all objects/methods and actually create an instance of the DAO to use it.
What are the benefits of using singleton vs. all static methods? Now that I understand how to create one, I really don't see the benefit, rather, it seems worse to have to actually create an instance before usage...
...or maybe I just missed the boat when they were handing out singletons...
[ June 27, 2003: Message edited by: David Yutzy ]
 
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What are the benefits of using singleton vs. all static methods? Now that I understand how to create one, I really don't see the benefit, rather, it seems worse to have to actually create an instance before usage...
A class with all static methods is considered a pure utility class and as such is much less flexible than the Singleton. It's tempting to overuse the classes with all static methods, especially if you have a procedural programming background, not realizing that it breaks the OOP paradigm.
Unlike the class with all static data, you can subclass the Singleton and override its methods. It may also be easier to maintain state in the Singleton. The Singleton can also implement interfaces in a meaningful way. In addition, you can control the number of instances (for example, you may want to have one instance of the class per thread).
Finally, it's worth pointing out that both Singleton and the classes with all static methods are frequently abused. Before you write a Singleton or its equivalent, think carefully, -- should your class really be a singleton? Will it be the singleton if your requirements change or if you simply want to modify a particular part of your program? In many cases, you would realize that a better design would be not to put a constrain on your class, -- that will allow it to evolve easier.
Eugene.
 
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What are the benefits of using singleton vs. all static methods?
If a class is going to have any state or needs to implement a certain interface, go with a Singleton. For plain old utility classes, static methods are just fine.

From your description of a singleton, as I understand, we would have to change the code to use the .getInstance() method such as:
(code omitted)
If so, this would really suck having to go through all objects/methods and actually create an instance of the DAO to use it.

If you're using Eclipse, you can mostly automate the transition with the refactoring features.
First, create a getInstance() method and implement it.

Next use "Extract Method" to move the contents of each utility method into a different method and delegate any calls to the new method:

Here's the part you'll have to so yourself. Make all the newly extracted methods non-static.

Then updating all of your code to use the singleton is simply a matter of using Eclipse's automated "Inline" refactoring on the static methods.
 
David Yutzy
tumbleweed and gunslinger
Posts: 192
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The only time I've found that Eclipse complains about the "singleton" is in my DAO classes, which typically just call a Stored Procedure or execute some specialized Prepared Statements.
I've found there is no real need / benefit to extend or implement such classes as they are very specific to the project and highly customized.
These classes, however, do extend two other classes I've created called Database and jdbcConnection which service connections and other database specific functionality. Both of these sound like candidates for Singleton, but the DAO's do not.
Thank again to everyone for the info. It really cleared out the cobwebs!
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all:
First, what an answer of the sheriff!. Well, I have an annoying (is that a word?) custom to try to compile any code that I see, so I have to report the error:
this.contemt = content;
Undefined symbol contemt.
Anyway, the purpose of the post is to congratulate the sheriff for the Singleton explanation and to remind to David Yutzy that a DAO will not allways be relying on a RDBMS (it could be a file or better a legacy system), so not allways the jdbc connections will be the way to connect.
Please excuse my english and best regards to all.
 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Unlike the class with all static data, you can subclass the Singleton and override its methods. It may also be easier to maintain state in the Singleton. The Singleton can also implement interfaces in a meaningful way. In addition, you can control the number of instances (for example, you may want to have one instance of the class per thread).


I could subclass a class with all static methods and fields. I could override these static methods in the base class. I don't know what you really mean.

Thanks,
Chandana
 
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by chandana sapparapu:

I could subclass a class with all static methods and fields. I could override these static methods in the base class. I don't know what you really mean.

Thanks,
Chandana



Well, if we break your sentence into two parts,
1. I could subclass a class with all static methods and fields
2. I could override these static methods in the base class

1st one is right.
2nd one is wrong.

And thats why you got confused We can't "override" static methods. Static methods can only be shadowed. This means that see the following example,



Output
------
A.print()
A.print()
B.print()

Hopefully this explains it.

Thanks
Maulin
 
chandana sapparapu
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Maulin. Great explanation. In my example, I just tried Case 3 and it worked. It didn't occur to me to test case 2.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic