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. MES系统介绍

    为什么要引入MES系统? 随着ERP在企业应用的深入,ERP系统逐渐显示出其局限性.当ERP下达的工单到生产现场后,产品制造是以产线 "工单"或"批次"(Bat ...

  2. $emit的用法

    自定义事件$emit.使用$emit建立父子组件之间的通信.子组件到父组件之间的通信. 子组件: 父组件:

  3. vue3.0自定义指令(drectives)

    在大多数情况下,你都可以操作数据来修改视图,或者反之.但是还是避免不了偶尔要操作原生 DOM,这时候,你就能用到自定义指令. 举个例子,你想让页面的文本框自动聚焦,在没有学习自定义指令的时候,我们可能 ...

  4. [LeetCode]求两个链表的焦点--Intersection of Two Linked Lists

    标题题目地址 1.解题意 求解两个链表的焦点,这个交点并不是焦点的值相等,而是需要交点之后的数据是完全相等的. 落实到java层面,就是交点处的对象是同一个对象即可. ps:我最开始没有读懂题目,然后 ...

  5. 安装git之后,桌面出现蓝色问号的解决方法

    安装了git之后,桌面的图标全部变成蓝色的问号. 把隐藏的文件全部显示,也没有在桌面找到.git的文件, 解决步骤: 1.把隐藏的文件全部显示: 工具-文件夹选项-查看在"隐藏文件和文件夹& ...

  6. VC维相关知识

    假设空间H(Hypothesis Set) 输入空间D(X1...Xn) 1.增长函数(grown function) 是关于输入空间尺寸n的函数 假设空间对于D中所有实例实现分类(赋予标记)的分类方 ...

  7. linux系统修改不成功无法修改密码

    一.问题描述 新上架的浪潮服务器使用装机平台进行统一安装,安装完成后修改用户密码时统一无法修改,使用root账户无法修改其他用户密码,自身根密码也无法修改成功,报错如下 Changing passwo ...

  8. 记一次多事件绑定中自己给自己设置的坑——click,dblclick,mousedown,mousemove,mouseup

    目录 项目综述 需求 问题 猜想 解决 反思 项目综述 在页面中模拟某操作系统的操作界面,提供应用窗口的最大化.最小化.还原等功能 需求 对一个应用窗口标题栏双击使其铺满整个视口,再次双击还原到原来大 ...

  9. 知识图谱和neo4j的基本操作

    一.知识图谱的简介 1.知识图谱是什么 知识图谱本质上是语义网络(Semantic Network)的知识库 可以理解为一个关系图网络. 2.什么是图 图(Graph)是由节点(Vertex)和边(E ...

  10. docker基础总结

    搜索镜像docker search ubuntu 搜索ubuntu的Docker镜像 搜索结果单个单词ubuntu这样的镜像,被称为基础镜像或根镜像,这些基础镜像由 Docker 公司创建搜索结果ti ...