Singleton vs. Public class with static methods?
3 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Jason_Latta
Posted On:   Wednesday, December 4, 2002 05:52 AM

1. What is the difference between a singleton implementation vs. a public class with static methods?

2. What the pros/cons of each?

3. When should I use one implementation vs. the other?

Re: Singleton vs. Public class with static methods?

Posted By:   Anjan_Bacchu  
Posted On:   Wednesday, December 4, 2002 07:31 AM

Hi,


Singleton Implementation is usually done using public classes with static methods.



final public class Singleton {
static private final Singleton onlyInstance = Singleton();

private Singleton() {
}

public Singleton getInstance() {
return onlyInstance;
}
}





final public class Singleton2 {
static private Singleton2 onlyInstance = null;
private Object monitor = new Object();
private Object prop1 = null;

private Singleton2() {
}

public synchronized Singleton2 getInstance() {
if (null = onlyInstance) {
onlyInstance = new Singleton2();
}
return onlyInstance;
}

public void setProp1(Object prop1) {
this.prop1 = prop1;
}


public Object getProp1() {
return this.prop1;
}
}





Coming to your question, you can use public class with static methods if you are
happy with the synchronization behavior that comes with it. But if you want to have
semantics which come with instance based synchronization, then you may want to use
one of the usual Singleton() implementations. One of the advantages of using
the Singleton classes() is to force single-point access to the class. It also helps
doing lazy-loading of the instance(and resources) like in the above example2, if required.



My 2 cents



Best Regards

Re: Singleton vs. Public class with static methods?

Posted By:   Steven_Martin  
Posted On:   Wednesday, December 4, 2002 07:06 AM

Also, a static method implementation will not allow you to use inheritance.

Re: Singleton vs. Public class with static methods?

Posted By:   Bozidar_Dangubic  
Posted On:   Wednesday, December 4, 2002 06:46 AM

There really is a single issues here that you need to think about and that is shared data. If you do not have shared data and you are talking about being able to invoke utility methods which operate strictly on constants or data that you are passing to methods then static methods are a perfect solution for you (java.lang.Math is a perfect example of one such class).


If on the other hand you have shared data that needs to be accessed by several clients then you need a singleton, i.e. if your class has attributes and you want only one of such classes in your application, static method in a class is not a good solution. You could work with syncronization and come up with a solution where public static methods may still give you a workable solution but it won't be pretty.

About | Sitemap | Contact