factory as singleton

Hi,

I have one question in implementing a factory as singleton.

case 1 implementaion:

public class TestFactory{

public static TestFactory factory = new TestFactory();

private TestFactory()

{

// do something...if there is a need

}

public Hi createSomething()

{}

}

case 2 implementation :

public class TestFactory{

private static TestFactory factory = null;

private TestFactory()

{

// do something...if there is a need

}

public static TestFactory getInstance()

{

if (factory == null)

factory = new TestFactory();

return factory;

}

public Hi createSomething()

{}

}

so here is my question.. what is the difference between the two implemenations..

Are they two are the same, but just representing differently..or is there is any difference.. If there is,How should I decide which one to implement? what are the effects?

As I knew jvm takes some time to initialize the static fields. So if we use the static fields before it is initialized we might get some problems.So in my openion case2 is better than case1.am I right?

thanks in advance,

[1279 byte] By [jvramana] at [2007-9-27 4:19:04]
# 1

The only difference that I see, is that you are implementing a lazy initialization in the second case. Note: assuming that this code was omitted from case 1:

public static TestFactory getInstance()

{

return factory;

}

There is a trade off when you do this. You allocate the resources for your factory class when the Factory class is loaded vs. when it is instanciated. If you know that every time your app. is deployed you will instanciate this factory, I would say the first is better, but if this class is not always used (perhaps another factory is used in its place) use the lazy init case. It seems trivial, but perhaps if you have many different factories that are heavy on resources and you only use one per deployment, it could make sense to use case 2.

Hope this helps.

mkeenan17 at 2007-7-5 3:54:20 > top of Java-index,Other Topics,Patterns & OO Design...
# 2

The first is without a doubt better. The second will have threading issues because if one thread checks if the object is null and is then swapped out and a second thread comes in and checks the object, you will have double instantation of the factory. If you factory class can deal with being instantiated multiple times then you should be okay with step 2.

DatBean at 2007-7-5 3:54:20 > top of Java-index,Other Topics,Patterns & OO Design...