tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Design Patterns > Java Design Patterns > Registry Singleton

Registry Singleton 

This example shows creating a registry singleton. It helps to have module specific singletons.

File Name  :  
com/bethecoder/tutorials/dp/singleton/registry/RegistrySingleton.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.dp.singleton.registry;

import java.util.HashMap;
import java.util.Map;

public class RegistrySingleton {

  private static Map<String, RegistrySingleton> registry = new HashMap<String, RegistrySingleton>();
  private String moduleName = null;

  /**
   * Make sure to have private default constructor.
   * This avoids direct instantiation of class using 
   * new keyword/Class.newInstance() method
   */
  private RegistrySingleton() {
  }
  
  public static synchronized RegistrySingleton getInstance(String moduleName) {
    
    RegistrySingleton instance = null;
    
    if (registry.containsKey(moduleName)) {
      instance =  registry.get(moduleName);
    else {
      instance = new RegistrySingleton();
      instance.moduleName = moduleName;
      registry.put(moduleName, instance);
    }
    
    return instance;
  }
  
  public String getModuleName() {
    return moduleName;
  }

  public String toString() {
    return "RegistrySingletonn : " + getModuleName();
  }

}
   

File Name  :  
com/bethecoder/tutorials/dp/singleton/registry/Test.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.dp.singleton.registry;

public class Test {
  
  public static void main (String [] args) {
    
    System.out.println(RegistrySingleton.getInstance("UI"));
    System.out.println(RegistrySingleton.getInstance("Server"));
    System.out.println(RegistrySingleton.getInstance("UI"));
    System.out.println(RegistrySingleton.getInstance("Admin"));
    System.out.println(RegistrySingleton.getInstance("Server"));
    
  }
}
   

It gives the following output,
RegistrySingletonn : UI
RegistrySingletonn : Server
RegistrySingletonn : UI
RegistrySingletonn : Admin
RegistrySingletonn : Server


                    Print

   



Books Recommendation

 
 
bl  br