标签:null struct const ISE pat cut object code equal
public class ServiceLocator extends Object {
private static final String ZOOKEEPER_SERVICE = "zookeeperService";
private static final String JNDI_SERVICE = "jndiService";
/**
* Service Locator Pattern【服务定位器模式】
*/
@Test
public void all() {
Service service = ServiceLocatorImpl.find(JNDI_SERVICE);
service.execute();
final Service jndi = ServiceLocatorImpl.find(JNDI_SERVICE);
assertEquals(jndi, service);
service = ServiceLocatorImpl.find(ZOOKEEPER_SERVICE);
service.execute();
}
}
/**
* 1)服务抽象
*/
interface Service {
String getId();
String getName();
void execute();
}
/**
* 2)服务实现
*/
@Slf4j
@Value(staticConstructor = "of")
class ServiceImpl implements Service {
private final String id;
private final String name;
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public void execute() {
log.info("{} {} is working", getId(), getName());
}
}
/**
* 3)服务缓存
*/
class ServiceCache {
private final ConcurrentMap<String, Service> services = new ConcurrentHashMap<>();
public Service find(String serviceId) {
return services.get(serviceId);
}
public void register(Service service) {
services.putIfAbsent(service.getId(), service);
}
}
/**
* 4)第三方服务查找器
*/
class ServiceLookup {
public static final Service lookup(String serviceId) {
if ("jndiService".equals(serviceId)) {
return ServiceImpl.of("jndiService", "serviceA");
} else if ("zookeeperService".equals(serviceId)) {
return ServiceImpl.of("zookeeperService", "serviceB");
}
throw new IllegalStateException("no valid service for " + serviceId);
}
}
/**
* 5)服务定位器
*/
class ServiceLocatorImpl {
private static ServiceCache serviceCache = new ServiceCache();
public static final Service find(String serviceId) {
Service service = serviceCache.find(serviceId);
if (service == null) {
synchronized (serviceCache) {
service = serviceCache.find(serviceId);
if (service == null) {
serviceCache.register(service = ServiceLookup.lookup(serviceId));
}
}
}
return service;
}
}
标签:null struct const ISE pat cut object code equal
原文地址:https://www.cnblogs.com/zhuxudong/p/10224694.html