I am currently implementing a game in which there are different types of maps. Being all maps, they naturally share certain attributes and methods, so an abstract class Map
was created, to then be subclassed by maps such as SafeMap
, HazardousMap
, WeirdMap
, etc.
To make it easy to add more maps in the future, the factory method design pattern was used. So the program contains a MapCreator
class whose code looks something like this:
public class MapCreator{
public Map createMap(char mapType){
switch(mapType){
case 'S':
return new SafeMap();
case 'H':
return new HazardousMap();
case 'W':
return new WeirdMap();
default:
return null;
}
}
}
Now I would also like to enforce that only one Map instance exists (regardless of the subclass chosen). I've read that the best way to go about this is to deploy the singleton design pattern, where a static instance is declared privately within the class and the constructor is also made private. But I do not know how this can be done in conjunction with the factory method design pattern, since we have multiple subclasses and getInstance()
has to be in a concrete class.
I appreciate any assistance.
Note: I have had a look at a few similar questions but I don't think the responses to those are relevant to my case.
The easiest way to do this is to use a single static field, and return that value if a map is already created.
Code is untested, but I think the concept is simple enough:
public class MapCreator{
private static Map theOnlyMap;
public synchronized Map createMap(char mapType){
if( theOnlyMap != null ) return theOnlyMap;
switch(mapType){
case 'S':
theOnlyMap = new SafeMap();
break;
case 'H':
theOnlyMap = new HazardousMap();
break;
case 'W':
theOnlyMap = new WeirdMap();
break;
}
return theOnlyMap;
}
}