Created
December 25, 2025 11:50
-
-
Save kadiryumlu/38ccafc89f791bc9c12d6ee45f9d0c4c to your computer and use it in GitHub Desktop.
ServiceLocator class for Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.HashMap; | |
| import java.util.Map; | |
| public final class ServiceLocator { | |
| private static final Map<Class<?>, Object> services = new HashMap<>(); | |
| private ServiceLocator() { | |
| // | |
| } | |
| public static <T> void register(Class<T> type, T service) { | |
| services.put(type, service); | |
| } | |
| public static <T> void unregister(Class<T> type) { | |
| services.remove(type); | |
| } | |
| @SuppressWarnings("unchecked") | |
| public static <T> T get(Class<T> type) { | |
| Object service = services.get(type); | |
| if (service != null) { | |
| return (T) service; | |
| } | |
| throw new RuntimeException("Service not found: " + type.getName()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment