I have written the code shown below:
public class SiteMapFactory {
public static ISiteMap getSiteMap(Locale loc) {
ISiteMap returnMap = null;
if (loc.equals(Locale.US)) {
returnMap = SiteMap_en_US.getInstance();
}
if(loc.equals(new Locale("es","US"))){
returnMap = SiteMap_en_US.getInstance();
}
if(loc.equals(Locale.CANADA)){
returnMap = SiteMap_fr_CA.getInstance();
}
return returnMap;
}
}
I want to return the same site map for both en_US (English) and es_US (Spanish) of our website. So I am instantiating the US sitemap for both Spanish and English version (a third party vendor is converting our English pages to Spanish). The way the site map is instantiated is using singleton. Singleton object is created as follows:
public class SiteMap_en_US extends SiteMapTree {
private static SiteMap_en_US m_instance;
private SiteMap_en_US() {}
static {
m_instance = new SiteMap_en_US();
m_instance.init();
}
public static SiteMap_en_US getInstance(){
return m_instance;
}
@Override
protected void init() {
//some code
}
}
My question is: can I reuse the same singleton object twice? Is it a valid way of instantiating the singleton object?
Yes, you can reuse the same singleton object.
However: If you do this, you should not have to include any special handling within the object to determine which language it is being used for, it should simply behave the same way all the time.
If you have to make it behave differently, consider creating a subclass of SiteMap_en_US (SiteMap_es_US perhaps) that is derived from SiteMap_en_US and has a small number of behaviors overridden.
It’s possible to do all sorts of locale checks within the object to determine its behavior, but I highly recommend considering a different approach that’s easier to maintain.