1 package org.columba.core.facade; 19 20 import java.util.Hashtable ; 21 import java.util.Map ; 22 23 import org.columba.api.exception.ServiceNotFoundException; 24 25 39 public class ServiceFacadeRegistry { 40 41 private static ServiceFacadeRegistry instance = new ServiceFacadeRegistry(); 42 43 private Map <Class , Service> map = new Hashtable <Class , Service>(); 44 45 private ServiceFacadeRegistry() { 46 } 47 48 public static ServiceFacadeRegistry getInstance() { 49 return instance; 50 } 51 52 public void register(Class serviceInterface, Object serviceInstance) { 53 Service service = new Service(serviceInterface, serviceInstance); 54 55 map.put(serviceInterface, service); 56 } 57 58 public void unregister(Class serviceInterface) { 59 map.remove(serviceInterface); 60 } 61 62 public Object getService(Class serviceInterface) 63 throws ServiceNotFoundException { 64 Object o = null; 65 Service service = null; 66 67 if (map.containsKey(serviceInterface)) { 69 service = map.get(serviceInterface); 70 71 if (service != null) 73 o = service.getServiceInstance(); 74 } 75 76 if (o == null) 77 throw new ServiceNotFoundException(serviceInterface); 78 79 return o; 80 } 81 82 90 private class Service { 91 private Class serviceInterface; 92 93 private String implementationName; 94 95 private Object serviceInstance; 96 97 Service(Class serviceInterface, String implementationName) { 98 this.serviceInterface = serviceInterface; 99 this.implementationName = implementationName; 100 } 101 102 public Service(Class serviceInterface, Object serviceInstance) { 103 this.serviceInterface = serviceInterface; 104 105 this.serviceInstance = serviceInstance; 106 } 107 108 111 public Object getServiceInstance() { 112 if (serviceInstance == null) { 115 serviceInstance = loadInstance(implementationName); 117 } 118 119 return serviceInstance; 120 } 121 122 125 public Class getServiceInterface() { 126 return serviceInterface; 127 } 128 129 137 private Object loadInstance(String className) { 138 Object object = null; 139 140 try { 141 Class clazz = this.getClass().getClassLoader().loadClass( 142 className); 143 144 object = clazz.newInstance(); 145 146 } catch (ClassNotFoundException e) { 147 148 e.printStackTrace(); 149 } catch (InstantiationException e) { 150 151 e.printStackTrace(); 152 } catch (IllegalAccessException e) { 153 154 e.printStackTrace(); 155 } 156 157 return object; 158 } 159 } 160 } | Popular Tags |