Click here to Skip to main content
15,886,872 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to java singleton, I want to make my class singleton, so that I have one instance of it in my code. The class which I want to be singleton is extend another class which its constructor have two entries, and entries are also singleton!

Below code is, what I have done! but it is not correct! how can I write my singleton

Java
public class Singleton extends Parent{
private Ui ui;
private Store store;
private singleton(Ui ui, Store store) {
    super(ui, store);
    // TODO Auto-generated constructor stub
}
private static class singletonHolder() {
    // My problem is here: how to set value for super class?!
    public static final singleton INSTANCE = new singleton();
}

public static singleton getInstance() {
    return singletonHolder.INSTANCE;
}

protected Object readResolve() {
    return getInstance();
}
public void SetStore(Store dstore){
    store = dstore;
}
public void SetUi(Ui uid){
    ui = uid;
} 
}
Posted
Comments
Anton Koekemoer 28-Jul-14 9:54am    
Could you please clarify what you mean by the statement

"The class which I want to be singleton is extend another class which its constructor have
two entries, and entries are also singleton!"

I can see that the parent class constructor requires two arguments, do you mean that the values for the arguments can be obtained from other singletons, in other words from a call like

Ui.getInstance() and Store.getInstance() ?
Coder93 28-Jul-14 10:20am    
yes

1 solution

Assuming that the Ui and Store classes are also implemented as Singleton, you could do it as follows.

Java
public class Singleton extends Parent{
  private Ui ui;
  private Store store;

  // Static field to hold the singleton instance 
  private static final singleton INSTANCE;

  // This is a static constructor. It will be executed once, when the class is 
  // loaded.  Use this to create an instance of your class for the singleton
  static {

     INSTANCE =  new Singleton(Ui.getInstance(), Store.getInstance());
  }

  // This is the constructor. You HAVE to pass the parameters to the base 
  // class (Parent), See the static constructor above.
  private Singleton(Ui ui, Store store) {
      super(ui, store);
  }

  public static singleton getInstance() {

      return INSTANCE;
  }
 
  protected Object readResolve() {

      return getInstance();
  }

  public void SetStore(Store dstore){

      store = dstore;
  }

  public void SetUi(Ui uid){

      ui = uid;
  } 
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900