O'Reilly Forums: Singleton V/s Class With Static Members & Methods - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Singleton V/s Class With Static Members & Methods

#1 User is offline   Ranjan Maheshwari 

  • New Member
  • Pip
  • Group: Members
  • Posts: 1
  • Joined: 05-October 12

Posted 05 October 2012 - 11:31 PM

Why would one ever require one and only one instance? Same purpose can be achieved using classes with static member variables and static methods. As far as I can understand the difference between the two is Polymorphism.

It would be really helpful if someone can provide an example from real life scenario or from any Java API where Singleton objects need to participate in Polymorphism?
0

#2 User is offline   hgilson 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 12
  • Joined: 08-October 10

Posted 24 October 2012 - 08:55 AM

Ranjan,

Often, singleton pattern classes are used to broker concurrent access to a shared resource. You will see it in quite a few logger implementations. The pattern particularly useful if you have a an "expensive" resource that might not be needed during the course of the application. Since the singleton supports "lazy initialization," you only pay the cost for the resource if you actually need it. Also, supporting polymorphism for an object can be useful :).

Here are some difference between using classes with static methods and variables:
1. Singletons can implement interfaces and inherit from other classes.
2. Singletons can be lazy loaded. Only when it is actually needed. That's very handy if the initialization includes expensive resource loading or database connections.
3. Singletons can be extended into a factory. The object management behind the scenes is abstract so it's better maintainable and results in better code.

Of course, don't use this as license to go "Singleton" wild. As with most design patterns, the patterns pros and cons must be carefully considered before implementation.

H.

View PostRanjan Maheshwari, on 05 October 2012 - 11:31 PM, said:

Why would one ever require one and only one instance? Same purpose can be achieved using classes with static member variables and static methods. As far as I can understand the difference between the two is Polymorphism.

It would be really helpful if someone can provide an example from real life scenario or from any Java API where Singleton objects need to participate in Polymorphism?

0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users