The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
February 2002

Advertisement

Advertisement

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

Message:

Problems with Singletons and Static References

Posted by Matt Gerrans on February 22, 2002 at 1:39 PM


> I'm trying to implement a class that uses a static method to return an instance of itself to the calling object. It's not precisely a singleton because it can also be instantiated via a call to a constructor.

> I've gotten it to work more or less correctly, but I'm having trouble with methods in the instance that access non-static variables:

> The pertinent code follows:


> public class GeneManager {

> private GeneManagerGUI gui;

> private static GeneManager manager;
> private static boolean initialized = false;
>
> public GeneManager() {
> this.manager = this;
> initialized = true;
> }



I don't see the pertinent part; you said "I'm having trouble with methods in the instance that access non-static variables," but I don't see any methods besides the constructor and the only non-static variable I see is gui, which isn't accessed anywhere in the sample. The only bug I see is that you are prefixing a class variable with "this." which probably doesn't compile; you should have manager = this; in place of this.manager = this;

Note that if you have some static getInstance() method, then the instance it returns will not always be the same one, it will always be the same as the last one instantiated -- this would be a non-standard implementation of getInstance() and thus should be prominently documented (or better, use a different method name like getLastInstantiatedInstance()).

Usually, if you really want a singleton, you'd make the constructor private (you probably already know this, since you did mention that it is not precisely a singleton).




Replies:

Sponsored Links



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