cancel
Showing results for 
Search instead for 
Did you mean: 

singleton object

Former Member
0 Kudos

What is singleton object used for? Can I use clonning for creation of another singleton object out of existing? If yes, then how can I restrict the use of clone method?

Accepted Solutions (1)

Accepted Solutions (1)

former_member185029
Active Contributor
0 Kudos

Hi,

1. Singleton classes allow only one instance of singleton object to exist. So if the requirement is for example, a central configuration object that stores setup information should have one and one only instance - a global copy accessible from any part of the application, including any threads that are running. Creating a new configuration object and using it would be fairly useless, as other parts of the application might be looking at the old configuration object, and changes to application settings wouldn't always be acted upon.

2. Yes clonning is supported by singleton classes (inherited from the super class Object). If you want to prevent user from using clone method, you will have to override this method in your singleton class.

Hope that helps,

Ashutosh.

Former Member
0 Kudos

Thanks buddy, that was quit a good help.

BBnu

Former Member
0 Kudos

Hello,

A singleton is usually implemented like this:


public class MySingletonClass {
    // Holder:
    private static MySingletonClass instance = new MySingletonClass();

    // Private constructor to prevent instantiation:
    private MySingletonClass() {
      // do something
    }

    // Use this method to retrieve the instance:
    public static MySingletonClass getInstance() { return instance; }

    // methods...
    public void doSomething() { ... }
}

You can call methods on the singleton object like this:

MySingletonClass.getInstance().doSomething();

I have to disagree slightly on your point 2.

An object will always throw a CloneNotSupportedException, unless it implements the Cloneable interface. There is no need to override the clone method, if you don't want to support cloning.

Best regards,

Daniel

Answers (0)