Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. @Service
  2. public class ServiceFactory {
  3.  
  4. @Autowired
  5. private List<PlatformService> services;
  6.  
  7. private static final Map<Class<? extends PlatformService>, PlatformService> singletonCache = new HashMap<>();
  8.  
  9. private static final Map<String, PlatformService> instanceCache = new HashMap<>();
  10.  
  11. @PostConstruct
  12. public void initializeSingletonCache() {
  13. services.forEach(service -> {
  14. singletonCache.put(service.getClass(), service);
  15. service.initialize();
  16. });
  17. }
  18.  
  19. public static <T extends PlatformService> T registerInstanceService(String serviceName, Class<T> service) throws RuntimeException, InstantiationException, IllegalAccessException {
  20. if (instanceServices.containsKey(serviceName)) {
  21. throw new RuntimeException("An instance with the name " + serviceName + " has already been created");
  22. }
  23.  
  24. T serviceObject = service.newInstance();
  25. instanceServices.put(serviceName, serviceObject);
  26. return serviceObject;
  27.  
  28. }
  29.  
  30. public static <T extends PlatformService> void registerInstanceService(String serviceName, T service) throws Exception {
  31. service.initialize();
  32. instanceServices.put(serviceName, service);
  33. }
  34.  
  35. public static <T extends PlatformService> T getService(Class<T> service) {
  36. return service.cast(singletonServices.get(service));
  37. }
  38.  
  39. public static Map<Class<? extends PlatformService>, PlatformService> getSingletonServices() {
  40. return singletonServices;
  41. }
  42.  
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement