• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1405
  • Last Modified:

Instantiate a Singleton class with parameters in contructor

I have a singleton class like

public class Singleton {

   private int innerInt;

   static private Singleton _instance = null;


   protected Singleton() {
   }

   static public Singleton instance() {
           if (_instance== null) {
      synchronized (Singleton.class) {
            if (_instance== null) {
                   _instance= new Singleton();
            }
      }
           }
           return _instance;
   }
}

The problem is that I need to set the value of innerInt in the constructor of the Singleton class when it is instantiated i.e. when instance() is called. Now i dont want everyone calling instance with a parameter.

I know one solution is to call instance() with a null parameter everytime but i was wondering if there is a more elegant solution to the problem.

Thanks.
0
thefallguy
Asked:
thefallguy
  • 5
  • 2
1 Solution
 
CEHJCommented:
Why not

static public Singleton instance(int i) {
    .....
}


?
0
 
CEHJCommented:
>>Now i dont want everyone calling instance with a parameter.

You can always overload instance()
0
 
CEHJCommented:
You can also set the attribute using a mutator method

Singleton s = Singleton.instance();
s.setInnerInt(10);
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
girionisCommented:
You could do:

protected Singleton() {
   if (innerInt == 0)
   {
        innerInt = 10;
    }
   }

this will work in all the cases apart the one that the user will try to set it to zero.
0
 
girionisCommented:
On the other hand, the constructor will only be called once (at least per classloader) so you could simply set the value

protected Singleton() {
         innerInt = 10;
 
   }
0
 
CEHJCommented:
Do you want the innerInt to be publicly mutable?
0
 
CEHJCommented:
8-)
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 5
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now