com.maxifier.mxcache.impl.instanceprovider.DefaultInstanceProvider Maven / Gradle / Ivy
/*
* Copyright (c) 2008-2014 Maxifier Ltd. All Rights Reserved.
*/
package com.maxifier.mxcache.impl.instanceprovider;
import com.maxifier.mxcache.InstanceProvider;
import com.maxifier.mxcache.NoSuchInstanceException;
import gnu.trove.map.hash.THashMap;
import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.Map;
/**
* @author Alexander Kochurov ([email protected])
*/
public final class DefaultInstanceProvider implements InstanceProvider {
private static final DefaultInstanceProvider INSTANCE = new DefaultInstanceProvider();
private final Map registry = Collections.synchronizedMap(new THashMap());
private DefaultInstanceProvider() {}
public static DefaultInstanceProvider getInstance() {
return INSTANCE;
}
public Binder bind(final Class t) {
return new BinderImpl(this, registry, t);
}
public void clearBinding(Class cls) {
registry.remove(cls);
}
@Nonnull
@SuppressWarnings({ "unchecked" })
@Override
public T forClass(@Nonnull Class cls) {
Provider provider = registry.get(cls);
if (provider == null) {
return createInstance(cls);
}
return (T) provider.get();
}
private static T createInstance(@Nonnull Class cls) {
try {
return cls.newInstance();
} catch (InstantiationException e) {
throw new NoSuchInstanceException(e);
} catch (IllegalAccessException e) {
throw new NoSuchInstanceException(e);
}
}
}