Skip to content

Instantly share code, notes, and snippets.

@marchy
Created January 13, 2015 16:29
Show Gist options
  • Save marchy/6bda172592ad6ae359a0 to your computer and use it in GitHub Desktop.
Save marchy/6bda172592ad6ae359a0 to your computer and use it in GitHub Desktop.
Strict Service Locator
public class ServiceLocator {
//
// instance fields
//
private final static Map<Class, Object> _Services;
//
// constructors
//
static {
_Services = new HashMap<Class, Object>();
}
//
// operations
//
public static void registerLocationService( LocationService locationService ){
registerSingletonService( locationService );
}
public static LocationService resolveLocationService() {
return resolveSingletonService( LocationService.class );
}
//
// private methods
//
private static <TService> void registerSingletonService( TService service ){
Preconditions.shouldNotBeNull( service, "service" );
// ensure service is not already registered
final Class<?> serviceClass = service.getClass();
if( _Services.get( serviceClass ) != null )
throw new IllegalStateException( String.format( "Service %s is already registered", service ));
_Services.put( serviceClass, service );
}
private static <TService> TService resolveSingletonService( Class serviceClass ){
Preconditions.shouldNotBeNull( serviceClass, "serviceClass" );
// ensure service is registered
if( !_Services.containsKey( serviceClass ))
throw new IllegalStateException( String.format( "No %s service registered", serviceClass.getSimpleName() ));
return (TService)_Services.get( serviceClass );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment