Singleton pattern question.

Hi guys. I`m developing a factory that has a factory method. The factory method receives a string (colorname) and retrieves its code from hashmap. I have two solutions. The first one is:

publicclass ColorFactory{

privatestatic HashMap colors=null;

privatestatic initializeColorsMap(){

colors =new HashMap();

//here i fill the map

...............................

}

publicstaticint getColorCode(String colorName){

if (colors ==null){

initializeColorsMap();

}

//here i retrieve the code ad return it

........

}

}

In this solution i use static methods. In he second solution i use the Singleton pattern to create a factory instance. The code is:

publicclass ColorFactory{

privatestatic ColorFactory factory =null;

private HashMap colors=null;

private initializeColorsMap(){

colors =new HashMap();

//here i fill the map

...............................

}

private ColorFactory(){

initializeColorsMap();

}

publicstatic ColorFactory getInstance(){

if (factory==null){

factory =new ColorFactory();

}

return factory;

}

publicint getColorCode(String colorName){

if (colors ==null){

initializeColorsMap();

}

//here i retrieve the code ad return it

........

}

}

Here i use singleton to create factory instance.

And the question is: where in the time the jvm allocates memory in the first and the second example code and what is the advantage of the singleton in this case?

Adrian Mitev

[3471 byte] By [amitteva] at [2007-10-2 17:04:40]
# 1

There seems little advantage in the singleton - the only advantage would be if you wanted to have a runtime option of a different implementation in the future (if you just wanted to change implementation, you could change the implementation of the static methods at the same cost as creating a new ColorFactory class), though in cases where there can be more than one of a thing the singleton is an antipattern. It's also perfectly possible to use the static method approach as a facade to a pluggable implementation if you do need to go that way in the future.

As you're not going to load the ColorFactory class until you call a method on it, and all the methods require initialisation, I'd go with:public class ColorFactory {

private static final HashMap colors;

static {

colors = new HashMap();

//here i fill the map

...............................

}

public static int getColorCode(String colorName) {

//here i retrieve the code ad return it

........

}

}

Pete

pm_kirkhama at 2007-7-13 18:19:02 > top of Java-index,Other Topics,Patterns & OO Design...