https://www.geeksforgeeks.org/service-locator-pattern/

Service Locator Pattern

Last Updated: 06-03-2018

The service locator pattern is a design pattern used in software development to encapsulate the processes involved in obtaining a service with a strong abstraction layer. This pattern uses a central registry known as the “service locator” which on request returns the information necessary to perform a certain task.
The ServiceLocator is responsible for returning instances of services when they are requested for by the service consumers or the service clients.

 
 
  • Service Locator : The Service Locator abstracts the API lookup services, vendor dependencies, lookup complexities, and business object creation, and provides a simple interface to clients. This reduces the client’s complexity. In addition, the same client or other clients can reuse the Service Locator.
  • InitialContext : The InitialContext object is the start point in the lookup and creation process. Service providers provide the context object, which varies depending on the type of business object provided by the Service Locator’s lookup and creation service.
  • ServiceFactory : The ServiceFactory object represents an object that provides life cycle management for the BusinessService objects. The ServiceFactory object for enterprise beans is an EJBHome object.
  • BusinessService : The BusinessService is a role that is fulfilled by the service the client is seeking to access. The BusinessService object is created or looked up or removed by the ServiceFactory. The BusinessService object in the context of an EJB application is an enterprise bean.

Suppose classes with dependencies on services whose concrete types are specified at compile time.

In the above diagram, ClassA has compile time dependencies on ServiceA and ServiceB.But this situation has drawbacks.

  • If we want to replace or update the dependencies we must change the classes source code and recompile the solution.
  • The concrete implementation of the dependencies must be available at compile time.

By using the Service Locator pattern :

In simple words, Service Locator pattern does not describe how to instantiate the services. It describes a way to register services and locate them.

Let’s see an example of Service Locator Pattern.

filter_none

edit

play_arrow

brightness_4

// Java program to
// illustrate Service Design Service
// Locator Pattern
  
import java.util.ArrayList;
import java.util.List;
  
// Service interface
// for getting name and
// Executing it.
  
interface Service {
    public String getName();
    public void execute();
}
  
// Service one implementing Locator
class ServiceOne implements Service {
    public void execute()
    {
        System.out.println("Executing ServiceOne");
    }
  
    @Override
    public String getName()
    {
        return "ServiceOne";
    }
}
  
// Service two implementing Locator
class ServiceTwo implements Service {
    public void execute()
    {
        System.out.println("Executing ServiceTwo");
    }
  
    @Override
    public String getName()
    {
        return "ServiceTwo";
    }
}
  
// Checking the context
// for ServiceOne and ServiceTwo
class InitialContext {
    public Object lookup(String name)
    {
        if (name.equalsIgnoreCase("ServiceOne")) {
            System.out.println("Creating a new ServiceOne object");
            return new ServiceOne();
        }
        else if (name.equalsIgnoreCase("ServiceTwo")) {
            System.out.println("Creating a new ServiceTwo object");
            return new ServiceTwo();
        }
        return null;
    }
}
  
class Cache {
    private List<Service> services;
  
    public Cache()
    {
        services = new ArrayList<Service>();
    }
  
    public Service getService(String serviceName)
    {
        for (Service service : services) {
            if (service.getName().equalsIgnoreCase(serviceName)) {
                System.out.println("Returning cached "
                                   + serviceName + " object");
                return service;
            }
        }
        return null;
    }
  
    public void addService(Service newService)
    {
        boolean exists = false;
        for (Service service : services) {
            if (service.getName().equalsIgnoreCase(newService.getName())) {
                exists = true;
            }
        }
        if (!exists) {
            services.add(newService);
        }
    }
}
  
// Locator class
class ServiceLocator {
    private static Cache cache;
  
    static
    {
        cache = new Cache();
    }
  
    public static Service getService(String name)
    {
        Service service = cache.getService(name);
  
        if (service != null) {
            return service;
        }
  
        InitialContext context = new InitialContext();
        Service ServiceOne = (Service)context.lookup(name);
        cache.addService(ServiceOne);
        return ServiceOne;
    }
}
  
// Driver class
class ServiceLocatorPatternDemo {
    public static void main(String[] args)
    {
        Service service = ServiceLocator.getService("ServiceOne");
        service.execute();
  
        service = ServiceLocator.getService("ServiceTwo");
        service.execute();
  
        service = ServiceLocator.getService("ServiceOne");
        service.execute();
  
        service = ServiceLocator.getService("ServiceTwo");
        service.execute();
    }
}

Output:

Creating a new ServiceOne object
Executing ServiceOne
Creating a new ServiceTwo object
Executing ServiceTwo
Returning cached ServiceOne object
Executing ServiceOne
Returning cached ServiceTwo object
Executing ServiceTwo

Advantages :

  • Applications can optimize themselves at run-time by selectively adding and removing items from the service locator.
  • Large sections of a library or application can be completely separated. The only link between them becomes the registry.

Disadvantages :

  • The registry makes the code more difficult to maintain (opposed to using Dependency injection), because it becomes unclear when you would be introducing a breaking change.
  • The registry hides the class dependencies causing run-time errors instead of compile-time errors when dependencies are missing.

Strategies

The following strategies are used to implement service Locator Pattern :

  • EJB Service Locator Strategy : This strategy uses EJBHome object for enterprise bean components and this EJBHome is cached in the ServiceLocator for future use when the client needs the home object again.
  • JMS Queue Service Locator Strategy : This strategy is applicable to point to point messaging requirements. The following the strategies under JMS Queue Service Locator Strategy.
    • JMS Queue Service Locator Strategy
    • JMS Topic Service Locator Strategy
  • Type Checked Service Locator Strategy : This strategy has trade-offs. It reduces the flexibility of lookup, which is in the Services Property Locator strategy, but add the type checking of passing in a constant to the ServiceLocator.getHome() method.

Design Pattern - Service Locator Pattern - Tutorialspoint https://www.tutorialspoint.com/design_pattern/service_locator_pattern.htm

Service Locator Pattern 服务定位的更多相关文章

  1. .NET 服务器定位模式(Service Locator Pattern)——Common Service Locator

    本文内容 场景 目标 解决方案 实现细节 思考 相关模式 更多信息 参考资料 Common Service Locator 代码很简单,它一般不会单独使用,而是作为一个单件模式,与像 .net Uni ...

  2. [Design Pattern] Service Locator Pattern 简单案例

    Service Locator Pattern,即服务定位模式,用于定位不同的服务.考虑到 InitialContext::lookup 的成本比较高,提供了 Cache 类缓存以定位到的服务. 代码 ...

  3. 《Prism 5.0源码走读》Service Locator Pattern

    在Prism Bootstrapper里面取实例的时候使用 ServiceLocator模式,使用的是CommonServiceLocator库 (http://commonservicelocato ...

  4. 服务定位器(Service Locator)

    服务定位器(Service Locator) 跟DI容器类似,引入Service Locator目的也在于解耦.有许多成熟的设计模式也可用于解耦,但在Web应用上, Service Locator绝对 ...

  5. Design Pattern - Service Locator Pattern--转载

    原文地址:http://www.tutorialspoint.com/design_pattern/service_locator_pattern.htm The service locator de ...

  6. Service Locator 模式

    什么是Service Locator 模式? 服务定位模式(Service Locator Pattern)是一种软件开发中的设计模式,通过应用强大的抽象层,可对涉及尝试获取一个服务的过程进行封装.该 ...

  7. Atitit。如何实现dip, di ,ioc ,Service Locator的区别于联系

    Atitit.如何实现dip, di ,ioc  ,Service Locator的区别于联系 1. Dip原则又来自于松耦合思想方向1 2. 要实现dip原则,有以下俩个模式1 3. Ioc和di的 ...

  8. 【转】Understanding Inversion of Control, Dependency Injection and Service Locator Print

    原文:https://www.dotnettricks.com/learn/dependencyinjection/understanding-inversion-of-control-depende ...

  9. PHP中应用Service Locator服务定位及单例模式

    单例模式将一个对象实例化后,放在静态变量中,供程序调用. 服务定位(ServiceLocator)就是对象工场Factory,调用者对象直接调用Service Locator,与被调用对象减轻了依赖关 ...

随机推荐

  1. MVC中使用AutoMapper

    参考博文 https://www.cnblogs.com/fred-bao/p/5700776.html 前言 通常在一个应用程序中,我们开发人员会在两个不同的类型对象之间传输数据, 通常我们会用DT ...

  2. 使用@Cacheable注解时,Redis连不上,直接调用方法内部的解决方案

    最近redis 域名一致解析错误,导致业务多了很多异常.那么如何在这种情况下直接访问数据库,而不是报错呢 1. 解决方案 其实很简单,在配置 redis 时,只需要多一项配置,继承 CachingCo ...

  3. (转) 增加 header 参数,spring boot + swagger2(springfox)

    1 @Configuration 2 @EnableSwagger2 3 public class Swagger2 { 4 @Bean 5 public Docket createRestApi() ...

  4. python函数----名称空间和作用域

    一 名称空间 名称空间即存放名字与对象映射/绑定关系的地方. 对于x=3,Python会申请内存空间存放对象3,然后将名字x与3的绑定关系存放于名称空间中,del x表示清除该绑定关系. ​在程序执行 ...

  5. filleSystemBasises

    基本查询命令 pwd 查看当前目录 dir 显示当前目录下的文件信息 more 查看文本文件的具体内容 cd 修改用户当前目录 mkdir 创建新的目录 rmdir 删除目录 copy filenam ...

  6. java反射-Method中的invoke方法的用法-以及函数式接口和lambda表达式

    作者最近研究框架底层代码过程中感觉自己基础不太牢固,于是写了一点案例,以防日后忘记 接口类:Animals 1 public interface Animals { 2 3 public void e ...

  7. 记一次flask上传文件返回200前端却504的问题

    前言 好久没写了, 主要是太忙了, 本篇记一下今天解决的一个问题吧, 耗了我大半天的时间才解决 问题 今天在调试代码时, 发现了一个诡异的问题, 我之前写了一个接口, 作用是接收上传的文件, 因为这个 ...

  8. Python requirements.txt 语法

    前言 之前一直苦于一个问题,比如一些包在Win上安装不了,比如 uvloop 但是为了提高效率,代码中必须有这个模块 在运行中可以通过 os 模块判断是否使用, 那依赖文件呢? requirement ...

  9. 详解 TCP的三次握手四次挥手

    本文转载来自https://blog.csdn.net/qzcsu/article/details/72861891 背景描述 通过上一篇中网络模型中的IP层的介绍,我们知道网络层,可以实现两个主机之 ...

  10. 【Linux】CentOS7中yumbackend.py进程的结束方法

    环境: CentOS Linux release 7.3.1611 (Core) 今天启动这个不怎么用的机器,才启动,就发现后台的yum无法进行安装,持续报这个错误 Loaded plugins: f ...