Design Pattern

Service Locator Pattern – Core J2EE Patterns

The design pattern, Service Locator is an important part in software development and it is core J2EE Design Patterns. Looking up for a service is one of the core features of service locator. A robust abstraction layer performs this function. The design pattern uses a central registry called Service Locator. When it is required to locate a number of services, through JNDI lookup, the service locator pattern is used.

Service Locator Pattern

The service locator pattern uses caching techniques in order to lookup JNDI for a certain service. This way, it reduces the overall looking up cost. When a service is needed to be looked up firstly, the service locator rummages in the JNDI. Then, then it catches the object. The lookups for services (or the same service) in the future is done by Service Locator in the cache. It ultimately enhances the working of the application.

Spring 5 Design Pattern Book

You could purchase my Spring 5 book that is with title name “Spring 5 Design Patterns“. This book is available on the Amazon and Packt publisher website. Learn various design patterns and best practices in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- “AUTHDIS40“.

UML Class Diagram for Service Locator

Let’s see the following class diagram for the Service Locator Pattern.

Use a Service Locator to implement and encapsulate service and component lookup. A Service Locator hides the implementation details of the lookup mechanism and encapsulates related dependencies.

There are certain entities involved in the service locator design pattern; service, context or initial context, service locator, cache, and client.

  • Service– The service object is responsible for storing the original service which is going to start working on the request. The reference to the required service is looked up in JNDI server.
  • Initial Context – The initial context object is responsible for storing the reference of the service that it uses in order to lookup.
  • Service Locator – The service locator object is the only point of communication in order to avail services through JNDI lookup which caches the services.
  • Cache – The cache object is responsible for storing the references to the services in order to re-utilize them later.
  • Client – The client object is responsible for invoking the service requests through the service locator.

The service locator pattern adds the code during the runtime, the app does not need to be recompiled. In some cases, you don’t even need to restart is.

Sample Implementation for Service Locator Design Pattern

Let’s see the following example for implementation of the Service Locator Design Pattern.

Step 1: Let’s create Service interface for a Business Service.

BusinessService.java

/**
 * 
 */
package com.doj.patterns.j2ee.servicelocator;

/**
 * @author Dinesh.Rajput
 *
 */
public interface BusinessService {
	
	public String getServiceName();
	
	public void executeService();
}

Step 2: Let’s create concrete classes for the business services i.e. Operation Business Service and Client Business Service.

OperationBusinessService.java

/**
 * 
 */
package com.doj.patterns.j2ee.servicelocator;

/**
 * @author Dinesh.Rajput
 *
 */
public class OperationBusinessService implements BusinessService {

	@Override
	public String getServiceName() {
		return "Operation";
	}

	@Override
	public void executeService() {
		System.out.println("Executing Business Service for Operation Team");
	}

}

ClientBusinessService.java

/**
 * 
 */
package com.doj.patterns.j2ee.servicelocator;

/**
 * @author Dinesh.Rajput
 *
 */
public class ClientBusinessService implements BusinessService {

	@Override
	public String getServiceName() {
		return "Client";
	}

	@Override
	public void executeService() {
		System.out.println("Executing Business Service for Client");
	}

}

Step 3: Let’s create a context class i.e. InitialContext for JNDI lookup

InitialContext.java

/**
 * 
 */
package com.doj.patterns.j2ee.servicelocator;

/**
 * @author Dinesh.Rajput
 *
 */
public class InitialContext {
	
	public Object lookup(String jndiName){
		   
		if(jndiName.equalsIgnoreCase("OPERATION")){
			System.out.println("Looking up and creating a new OperationBusinessService object");
			return new OperationBusinessService();
		}else if (jndiName.equalsIgnoreCase("CLIENT")){
			System.out.println("Looking up and creating a new ClientBusinessService object");
			return new ClientBusinessService();
		}
		return null;			
	}
}

Step 4: Let’s create a services cache class.

ServicesCache.java

/**
 * 
 */
package com.doj.patterns.j2ee.servicelocator;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Dinesh.Rajput
 *
 */
public class ServicesCache {
	
	private List businessServices;

	public ServicesCache(){
		businessServices = new ArrayList<>();
	}

	public BusinessService getBusinessService(String serviceName){
	   
		for (BusinessService businessService : businessServices) {
			if(businessService.getServiceName().equalsIgnoreCase(serviceName)){
				System.out.println("Returning cached  " + serviceName + " object");
				return businessService;
			}
		}
		return null;
	}

	public void addBusinessService(BusinessService newBusinessService){
		boolean exists = false;
	      
		for (BusinessService businessService : businessServices) {
			if(businessService.getServiceName().equalsIgnoreCase(newBusinessService.getServiceName())){
				exists = true;
	         }
		}
		if(!exists){
			businessServices.add(newBusinessService);
		}
	}
}

Step 5: Let’s create Service Locator

ServiceLocator.java

/**
 * 
 */
package com.doj.patterns.j2ee.servicelocator;

/**
 * @author Dinesh.Rajput
 *
 */
public class ServiceLocator {
	
	private static ServicesCache servicesCache;

	   static {
		   servicesCache = new ServicesCache();		
	   }

	   public static BusinessService getBusinessService(String jndiName){

		   BusinessService businessService = servicesCache.getBusinessService(jndiName);

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

	      InitialContext context = new InitialContext();
	      BusinessService businessService2 = (BusinessService)context.lookup(jndiName);
	      servicesCache.addBusinessService(businessService2);
	      return businessService2;
	   }
}

Step 6: Let’s create a demo class that use ServiceLocator to demonstrate Service Locator Design Pattern.

ServiceLocatorPatternDemo.java

/**
 * 
 */
package com.doj.patterns.j2ee.servicelocator;

/**
 * @author Dinesh.Rajput
 *
 */
public class ServiceLocatorPatternDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		BusinessService businessService = ServiceLocator.getBusinessService("OPERATION");
		businessService.executeService();
		businessService = ServiceLocator.getBusinessService("CLIENT");
		businessService.executeService();
		businessService = ServiceLocator.getBusinessService("OPERATION");
		businessService.executeService();
		businessService = ServiceLocator.getBusinessService("CLIENT");
		businessService.executeService();	
	}

}

Step 7: Let’s run this demo class and verify the output.

Looking up and creating a new OperationBusinessService object
Executing Business Service for Operation Team
Looking up and creating a new ClientBusinessService object
Executing Business Service for Client
Returning cached  OPERATION object
Executing Business Service for Operation Team
Returning cached  CLIENT object
Executing Business Service for Client

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago