Singleton?
Hello everyone,
I'm writing a Swing application where I use JFrame, InternalFrames and Dialogs. All of these things need to have an Icon set so that's why I wrote a class to do this. Namely the one provided with this question. Now I'm not entirely happy with this approach because everytime I need one of the methods I have to reinstantiate this class and this I believe is not good for performance. Now I was thinking if maybe making a Singleton of this class could be a solution and how would I go about it? It's being instantiated 5 times in my application. Is there an easy answer to my question?
package swingGUI;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
publicclass ImageDelegate{
public ImageDelegate(){
}
publicstatic ImageIcon setIcon(String url){
URL iconURL = Thread.currentThread().getContextClassLoader().getResource(url);
ImageIcon icon =new ImageIcon(iconURL);
return icon;
}
publicstaticvoid setImageIcon(String url, JFrame frame){
frame.setIconImage((setIcon(url)).getImage());
}
publicstaticvoid setImageIcon(String url, JDialog dialog){
dialog.setIconImage((setIcon(url)).getImage());
}
}
[2517 byte] By [
rockarenaa] at [2007-11-27 7:05:58]

> Yes. You have a class that doesn't have anything
> except static members. So there isn't any point in
> instantiating it even once.
Very true, however should you need a Singleton classpublic class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
dwga at 2007-7-12 18:57:13 >

> Why not:
> > public class Singleton {
> private static Singleton instance = new
> Singleton();
>
>private Singleton() {
> }
>
>public static Singleton getInstance() {
>return instance;
> }
> }
>
> Because it would be simpler and thread-safe. We don't want that. ;)
Well I was thinking don't create the instance until someone actually needs it, and there was no talk of this being needed for multi threading purposes.
In which case:
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
would do the job as well as the suggested alternative, although to be frank I really have no preference between the two options.
dwga at 2007-7-12 18:57:13 >

> > well, either isn't a true singleton of course (as
> > such a thing doesn't exist in Java except within
> the
> > scope of a particular classloader) :)
>
> Time to do a global search and replace. The
> Classloader Police are on to us!
welcome to the distributed world, where a single logical application instance consists of multiple physical application instances running on clustered machines.