Skip to content

Instantly share code, notes, and snippets.

@puke3615
Created July 14, 2021 08:30
Show Gist options
  • Save puke3615/c39630fe35ef9e64e59bb1d078bbbd1c to your computer and use it in GitHub Desktop.
Save puke3615/c39630fe35ef9e64e59bb1d078bbbd1c to your computer and use it in GitHub Desktop.
ServiceManager
import java.util.HashMap;
import java.util.Map;
/**
* 服务管理器<hr/>
* 1. 模块之间是相互独立的并列关系, 不能相互调用<br/>
* 2. 需要调用时, 通过下沉{@link Service}的方式<br/>
* <p>
*
* @author puke
* @version 2021/6/24
*/
@SuppressWarnings("unchecked")
public class ServiceManager {
private static final Map<Class<? extends Service>, Class<? extends Service>> IMPL_MAPPING = new HashMap<>();
private final Map<Class<? extends Service>, Service> instances = new HashMap<>();
public static void register(String interfaceName, String implName) {
try {
Class<?> interfaceType = Class.forName(interfaceName);
Class<?> implType = Class.forName(implName);
register(
(Class<? extends Service>) interfaceType,
(Class<? extends Service>) implType
);
} catch (ClassNotFoundException e) {
String format = String.format("Register failure, interface name is %s, impl name is %s",
interfaceName, implName);
throw new RuntimeException(format, e);
}
}
public static void register(Class<? extends Service> interfaceType,
Class<? extends Service> implType) {
IMPL_MAPPING.put(interfaceType, implType);
}
public <IS extends Service> IS getService(Class<IS> innerServiceType) {
Service innerService = instances.get(innerServiceType);
if (innerService != null) {
return (IS) innerService;
}
Class<? extends Service> implType = IMPL_MAPPING.get(innerServiceType);
if (implType == null) {
throw new RuntimeException(
String.format("No service registered for %s.", innerServiceType.getName())
);
}
try {
IS instance = (IS) implType.newInstance();
this.instances.put(innerServiceType, instance);
return instance;
} catch (Exception e) {
throw new RuntimeException("Create inner service instance failure.", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment