[Design Pattern] Service Locator Pattern 簡單案例

Service Locator Pattern,即服務定位模式,用於定位不一樣的服務。考慮到 InitialContext::lookup 的成本比較高,提供了 Cache 類緩存以定位到的服務。緩存

代碼實現ide

Service 接口spa

public interface Service {

    public String getName();
    
    public void execute();
}

Service1, Service2 實現 Service 接口,提供具體服務code

public class Service1 implements Service {

    private String name = "service1";
    
    @Override
    public String getName() {
        return name;
    }

    @Override
    public void execute() {
        System.out.println(name + "executing");
    }
}

 

public class Service2 implements Service {

    private String name = "service2";

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void execute() {
        System.out.println(name + " executing");
    }
}

InitialContext 用於查找並初始化服務htm

public class InitialContext {

    public static Service lookup(String jndiName){
        
        System.out.println(" initializing " + jndiName);
        
        if (jndiName.equals("service1")){
            return new Service1();
        }
        else if(jndiName.equals("service2")){
            return new Service2();
        }
        else{
            System.out.println("cannot find " + jndiName);
        }
        
        return null;
    }
}

ServiceLocator 是在 InitialConext 以前的一個層,把已找到的服務緩存起來,避免重複建立服務。blog

public class ServiceLocator {

    private static Cache cache = new Cache();
    
    public static Service getService(String serviceName){
        Service service = cache.getService(serviceName);
        
        if (service == null){
            service = InitialContext.lookup(serviceName);
            cache.addService(service);
        }    
        return service;
    }    
}

演示服務定位模式。接口

public class ServiceLocatorPatternDemo {

    public static void main() {
        Service service = ServiceLocator.getService("service1");
        service.execute();

        service = ServiceLocator.getService("service2");
        service.execute();

        service = ServiceLocator.getService("service1");
        service.execute();
        
        service = ServiceLocator.getService("service2");
        service.execute();
    }
}

 

注:get

爲了簡化模式關係演示,本案例沒有處理找不到服務的狀況,能夠在 InitialContext::lookup 和 ServiceLocator::getService 方法聲明爆出異常,交由客戶端代碼處理服務沒法找到的狀況。it

 

參考資料class

Design Pattern - Service Locator Pattern, TutorialsPoint

相關文章
相關標籤/搜索