1. 程式人生 > >服務定位器【其他模式】

服務定位器【其他模式】

null con ons per nds throw zook fin info

服務定位器

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;
    }
}

服務定位器【其他模式】