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

