码迷,mamicode.com
首页 > 其他好文 > 详细

服务定位器【其他模式】

时间:2019-01-05 15:46:41      阅读:171      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!