The Artima Developer Community
Sponsored Link

Legacy Design Forum
Designing with Static Members

Advertisement

Advertisement

This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Re: Singletons in Java

Posted by Steve Klingsporn on October 27, 2001 at 11:07 PM


You can do something like this:

public class Stack
{
private static Stack mInstance = null;

private Stack()
{
}

public static final Stack getInstance()
{
if (mInstance == null)
mInstance = new Stack();
return mInstance;
}
}

Basically, you always retrieve the singleton instance of Stack by going like this in your code:

Stack theStack = Stack.getInstance();

You use a static method, and the constructor is private so that other classes cannot instantiate it. The singleton instance is stored as a static reference.

Hope this helps. I realize it's being answered several years after the question was asked.



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us