6

Do I have to use private constructor to make a class singleton? Is there any other way than using private constructor? Can't I make a class singleton using public constructor?

2

6 Answers 6

7

If your class has a public constructor, then anybody can create an instance of it at any time. So it's not a singleton any more. For a singleton, there can exist only one instance.

Sign up to request clarification or add additional context in comments.

Comments

4

The reason it has to be a private constructor is because you want to prevent people from using it freely to create more than one instance.

A public constructor is possible only if you are able to detect an instance already exist and forbid a another instance being created.

Is there no way other than using private constructor ? Can't we make a class singleton using public constructor ?

Yes, it is actually possible, for example:

class Singleton
{
    private static Singleton instance = null;
    public Singleton() throws Exception    //Singleton with public constructor
    {
       if(instance != null)
          throw new Exception("Instance already exist");      
       //Else, do whatever..such as creating an instance
    }
}

1 Comment

Remarks: A standard singleton class will have private constructor and a getInstance() method. Assuming OP already know those things and is asking for possibilities of using public constructor, what was given will be what OP is asking for.
2

One way to create Singleton object using public constructor with throw exception from constructor if object is already exist.

For Example:

public class Singleton {

private static Singleton singleton;
private String hello;

public Singleton() throws Exception {
    if (singleton != null) {
        throw new Exception("Object already exist");
    }
}

public static Singleton getInstance() throws Exception {
    if (singleton == null) {
        singleton = new Singleton();
    }
    return singleton;
}

public String getHello() {
    return hello;
}

public void setHello(String hello) {
    this.hello = hello;
}

public static void main(String[] args) {
    try {

        Singleton single1 = Singleton.getInstance();
        single1.setHello("Hello");
        System.out.println(single1.getHello());

        Singleton single2 = Singleton.getInstance();
        System.out.println(single2.getHello());

        Singleton single3 = new Singleton();
        System.out.println(single3.getHello());


    } catch (Exception ex) {

    }
}

}

1 Comment

The key principle in your solution is exactly the same as what I have already provided.
2

If you really must use public constructor, then you should check whether instance is null and throw an exception.

if(instance != null)

Comments

0

Generally, Singleton pattern is used when you should have exactly 1 object of a class (e.g. Factories are very often implemented as Singletons).

public modifier allows anyone to access your method (as well as your constructor). In that case, anyone can create an instance of your class, thus it won't be a singleton anymore. By setting private modifier to your constructor, you are sure, it cannot be used outside of the class - no one will create any more objects of that class.

public class SingletonExample {
  private static final SingletonExample instance;

  // Initialize instance object in static block - done while loading the class by class loader
  static {
    instance = new SingletonExample();
  }

  private SingletonExample(){}

  public static SingletonExample getInstance(){
    return instance;
  }

  // Method used to create java.test.DateFormat using Oracle SQL Date pattern
  public DateFormat createDateFormat(String mask){
    if("DD-MM-YYYY HH24:MI:SS".equals(mask)){
      return new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    } else if("DD-MM-YYYY".equals(mask)){
      return new SimpleDateFormat("dd-MM-yyyy");
    } else {
      throw new UnsupportedOperationException("Unsupported mask - " + mask);
    }
  }
}

And usage example

public class SingletonExampleTest{
  public static void main(String... args){
    java.util.Date date = Calendar.getInstance().getTime();
    SingletonExample singleton = SingletonExample.getInstance();
    String mask = "DD-MM-YYYY";
    DateFormat df = singleton.createDateFormat(mask);
    System.out.println(df.format(date));
  }
}

Comments

-1

The private constructor is a reason, why your class is Singleton.

This Example shows pretty well, how you can use your Singleton class by using getInstance()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.