Service Locator Pattern and Java Implementation – 服务定位器模式和Java实现

最后修改: 2018年 4月 30日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

In this tutorial, we’re going to learn about the Service Locator design pattern in Java.

在本教程中,我们将学习Java中的服务定位器设计模式

We’ll describe the concept, implement an example and highlight the pros and cons of its use.

我们将描述这个概念,实现一个例子,并强调其使用的优点和缺点。

2. Understanding the Pattern

2.了解模式

The purpose of the Service Locator pattern is to return the service instances on demand. This is useful for decoupling service consumers from concrete classes.

服务定位器模式的目的是按需返回服务实例。这对于将服务消费者与具体类解耦非常有用。

An implementation will consist of the following components:

一个实施方案将由以下部分组成。

  • Client – the client object is a service consumer. It’s responsible for invoking the request from the service locator
  • Service Locator – is a communication entry point for returning the services from the cache
  • Cache – an object for storing service references to reuse them later
  • Initializer – creates and registers references to services in the cache
  • Service – the Service component represents the original services or their implementation

The original service object is looked up by the locator and returned on demand.

原始服务对象由定位器查找并按要求返回。

3. Implementation

3.实施

Now, let’s get practical and have a look at the concepts through an example.

现在,让我们实际一点,通过一个例子来看看这些概念。

First, we’ll create a MessagingService interface for sending messages in different ways:

首先,我们将创建一个MessagingService接口,用于以不同方式发送消息。

public interface MessagingService {

    String getMessageBody();
    String getServiceName();
}

Next, we’ll define two implementations of the interface above, that send messages through email and SMS:

接下来,我们将定义上述接口的两个实现,即通过电子邮件和短信发送消息。

public class EmailService implements MessagingService {

    public String getMessageBody() {
        return "email message";
    }

    public String getServiceName() {
        return "EmailService";
    }
}

The SMSService class definition is similar to the EmailService class.

SMSService类的定义与EmailService类类似。

After defining the two services, we have to define the logic to initialize them:

在定义了这两个服务后,我们必须定义逻辑来初始化它们。

public class InitialContext {
    public Object lookup(String serviceName) {
        if (serviceName.equalsIgnoreCase("EmailService")) {
            return new EmailService();
        } else if (serviceName.equalsIgnoreCase("SMSService")) {
            return new SMSService();
        }
        return null;
    }
}

The last component we need before putting the service locator object together is the cache.

在把服务定位器对象放在一起之前,我们需要的最后一个组件是缓存。

In our example, this is a simple class with a List property:

在我们的例子中,这是一个带有List属性的简单类。

public class Cache {
    private List<MessagingService> services = new ArrayList<>();

    public MessagingService getService(String serviceName) {
        // retrieve from the list
    }

    public void addService(MessagingService newService) {
        // add to the list
    }
}

Finally, we can implement our service locator class:

最后,我们可以实现我们的服务定位器类。

public class ServiceLocator {

    private static Cache cache = new Cache();

    public static MessagingService getService(String serviceName) {

        MessagingService service = cache.getService(serviceName);

        if (service != null) {
            return service;
        }

        InitialContext context = new InitialContext();
        MessagingService service1 = (MessagingService) context
          .lookup(serviceName);
        cache.addService(service1);
        return service1;
    }
}

The logic here is fairly simple.

这里的逻辑相当简单。

The class holds an instance of the Cache. Then, in the getService() method, it will first check the cache for an instance of the service.

该类持有一个Cache的实例。然后,在getService()方法中,它将首先检查缓存中的服务实例。

Then, if that’s null, it will call the initializing logic and add the new object to the cache.

然后,如果那是null,它将调用初始化逻辑并将新对象添加到缓存中。

4. Testing

4.测试

Let’s see how we can obtain instances now:

让我们看看我们现在如何获得实例。

MessagingService service 
  = ServiceLocator.getService("EmailService");
String email = service.getMessageBody();

MessagingService smsService 
  = ServiceLocator.getService("SMSService");
String sms = smsService.getMessageBody();

MessagingService emailService 
  = ServiceLocator.getService("EmailService");
String newEmail = emailService.getMessageBody();

The first time we get the EmailService from the ServiceLocator a new instance is created and returned. Then, after calling it the next time the EmailService will be returned from the cache.

我们第一次从ServiceLocator获得EmailService的时候,会创建一个新的实例并返回。然后,在下次调用它之后,EmailService将从缓存中返回。

5. Service Locator vs Dependency Injection

5.服务定位器与依赖性注入

At first glance, the Service Locator pattern may look similar to another well-known pattern – namely, Dependency Injection.

乍一看,服务定位器模式可能与另一个著名的模式相似–即依赖注入。

First, it’s important to note that both Dependency Injection and the Service Locator pattern are implementations of the Inversion of Control concept.

首先,需要注意的是,依赖注入和服务定位模式都是控制反转概念的实现

Before going further, learn more about Dependency Injection in this write-up.

在进一步讨论之前,请在本篇文章中了解更多关于依赖性注入的信息

The key difference here is that the client object still creates its dependencies. It just uses the locator for that, meaning it needs a reference to the locator object.

这里的关键区别在于,客户对象仍然创建其依赖关系。它只是使用了定位器,这意味着它需要一个对定位器对象的引用。

By comparison, when using the dependency injection, the class is given the dependencies. The injector is called only once at startup to inject dependencies into the class.

相比之下,当使用依赖性注入时,类被赋予了依赖性。注入器只在启动时被调用一次,以将依赖注入类中。

Finally, let’s consider a few reasons to avoid using the Service Locator pattern.

最后,让我们考虑一下避免使用服务定位器模式的几个原因。

One argument against it is that it makes unit testing difficult. With dependency injection, we can pass mock objects of the dependent class to the tested instance. On the other hand, this is a bottleneck with the Service Locator pattern.

反对它的一个理由是,它使单元测试变得困难。通过依赖注入,我们可以将依赖类的模拟对象传递给被测实例。另一方面,这也是服务定位器模式的一个瓶颈。

Another issue is that it’s trickier to use APIs based on this pattern. The reason for this is that the dependencies are hidden inside the class and they’re only verified at runtime.

另一个问题是,使用基于这种模式的API会比较麻烦。其原因是,依赖关系隐藏在类的内部,只有在运行时才被验证。

Despite all of this, the Service Locator pattern is easy to code and understand, and can be a great choice for small applications.

尽管这样,服务定位器模式很容易编码和理解,对于小型应用来说是一个很好的选择。

6. Conclusion

6.结论

This guide shows how and why to use the Service Locator design pattern. It discusses the key differences between the Service Locator design pattern and Dependency Injection concept.

本指南展示了如何以及为什么使用服务定位器设计模式。它讨论了服务定位器设计模式与依赖注入概念之间的主要区别。

In general, it’s up to the developer to choose how to design the classes in the application.

一般来说,由开发者来选择如何设计应用程序中的类。

Service Locator pattern is a straightforward pattern to decouple the code. However, in case of using the classes in multiple applications, dependency injection is a right choice.

服务定位器模式是一种直接的模式,可以将代码解耦。然而,如果要在多个应用程序中使用这些类,依赖注入是一个正确的选择。

As usual, the complete code is available in the Github project.

像往常一样,完整的代码可以在Github项目中获得。