PDA

View Full Version : One instance of a class


webguy08
05-12-2009, 02:44 AM
Hi all,
I'm writing a Java program and I need some of the classes to only have one instance ever created, but should allow the methods within it to be called as many times as required. How would I achieve this? I have tried looking around the internet but am unsure what the best approach would be.

Thanks for any help :)

Fou-Lu
05-12-2009, 07:05 AM
By using a singleton pattern. Lets see if I can find a link... this one looks pretty good: http://en.wikipedia.org/wiki/Singleton_pattern

The way to do this is by using a constructor that does not allow external calling (private or protected). Unlike PHP, java will let you reduce the scope of an inherited constructor.
Then you write an accessing method that looks to see if an object already exists. This should be static. Return if it exists, otherwise construct. Something like this:

public class MyClass
{
private static MyClass instance;
private MyClass(){}

public static MyClass createInstance()
{
if (MyClass.instance == null)
{
// instance does not currently exist, so lets create it:
MyClass.instance = new MyClass();
}
return MyClass.instance;
}
}

You can create a Singleton interface for the createInstance if you want. If you type it as a <? extends Singlton> that should let you get away with whatever you want for datatypes.

Hope I didn't mix my languages up too badly (I had to remove the :: calls lol).

webguy08
05-13-2009, 12:03 AM
Thanks for the help, but by doing this how do I create an instance of the class from another class? I need to have access to that createInstance() method and can't do so unless I construct an instance of it lol

Edit: Nevermind I've go it :thumbsup: