<p>The design pattern, <strong>Service Locator</strong> is an important part in software development and it is <strong><a href="https://dineshonjava.com/core-j2ee-patterns-best-design-practices/">core J2EE Design Patterns</a></strong>. 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.</p>
<h2>Service Locator Pattern</h2>
<p>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.</p>
<div style="background-color: #f2f9fc; border-radius: 3px; border: 1px solid #c9e6f2; line-height: 1.45; padding: 16px 16px 16px 16px;">
<h2 dir="ltr">Spring 5 Design Pattern Book</h2>
<div dir="ltr" style="color: #20124d; font-family: 'calibri' , sans-serif; font-size: 13pt; text-align: justify;">You could purchase my <strong>Spring 5 book</strong> that is with title name &#8220;<strong>Spring 5 Design Patterns</strong>&#8220;. This book is available on the <a href="https://www.amazon.in/Spring-Design-Patterns-Dinesh-Rajput/dp/1788299450/ref=sr_1_1?ie=UTF8&;qid=1507925340&;sr=8-1&;keywords=spring+5+design+pattern"><strong>Amazon</strong></a> and <a href="https://www.packtpub.com/application-development/spring-5-design-patterns"><strong>Packt</strong></a> publisher website. Learn various <strong>design patterns</strong> and <strong>best practices</strong> in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- &#8220;<strong>AUTHDIS40</strong>&#8220;.</div>
<div dir="ltr"></div>
<div dir="ltr"><a href="https://www.amazon.in/Spring-Design-Patterns-Dinesh-Rajput/dp/1788299450/ref=sr_1_1?s=books&;ie=UTF8&;qid=1512607966&;sr=1-1&;keywords=dinesh+rajput"><br />
<img class="aligncenter wp-image-3053 size-medium" title="Spring-5-Design-Pattern" src="https://i0.wp.com/dineshonjava.com/wp-content/uploads/2013/03/Spring-5-design-pattern.jpg?resize=243%2C300&;ssl=1" alt="Spring-5-Design-Pattern" width="243" height="300" /></a></div>
</div>
<h2>UML Class Diagram for Service Locator</h2>
<p>Let&#8217;s see the following class diagram for the Service Locator Pattern.</p>
<p><img class="aligncenter size-full wp-image-4054" src="https://dineshonjava.com/wp-content/uploads/2018/01/Service-Locator.gif" alt="Service Locator" width="490" height="374" /></p>
<p>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.</p>
<div style="text-align: left;">
<blockquote>
<p><strong>also read:</strong></p>
<ul style="text-align: left;">
<li><a title="https://dineshonjava.com/business-delegate/" href="https://dineshonjava.com/business-delegate/">Business Delegate Pattern</a></li>
<li><a title="https://dineshonjava.com/session-facade/" href="https://dineshonjava.com/session-facade/">Session Facade Pattern</a></li>
<li><a title="https://dineshonjava.com/business-object/" href="https://dineshonjava.com/business-object/">Business Object Pattern</a></li>
<li><a title="https://dineshonjava.com/composite-entity-pattern/" href="https://dineshonjava.com/composite-entity-pattern/">Composite Entity Pattern</a></li>
<li><a title="https://dineshonjava.com/transfer-object/" href="https://dineshonjava.com/transfer-object/">Transfer Object Pattern</a></li>
</ul>
</blockquote>
</div>
<p>There are certain entities involved in the service locator design pattern; <em>service</em>, <em>context or initial context,</em> <em>service</em> <em>locator</em>, <em>cache</em>, and <em>client</em>.</p>
<ul>
<li><strong>Service</strong>&#8211; 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.</li>
<li><strong>Initial Context</strong> &#8211; The initial context object is responsible for storing the reference of the service that it uses in order to lookup.</li>
<li><strong>Service Locator</strong> &#8211; The service locator object is the only point of communication in order to avail services through JNDI lookup which caches the services.</li>
<li><strong>Cache</strong> &#8211; The cache object is responsible for storing the references to the services in order to re-utilize them later.</li>
<li><strong>Client</strong> &#8211; The client object is responsible for invoking the service requests through the service locator.</li>
</ul>
<p>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.</p>
<h2>Sample Implementation for Service Locator Design Pattern</h2>
<p>Let&#8217;s see the following example for implementation of the Service Locator Design Pattern.</p>
<h3>Step 1: Let&#8217;s create Service interface for a Business Service.</h3>
<p><strong>BusinessService.java</strong></p>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.patterns.j2ee.servicelocator; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public interface BusinessService { 
	 
	public String getServiceName(); 
	 
	public void executeService(); 
} 
 
</pre>
<h3>Step 2: Let&#8217;s create concrete classes for the business services i.e. Operation Business Service and Client Business Service.</h3>
<p><strong>OperationBusinessService.java</strong></p>
<pre class="highlight">/** 
 * 
 */ 
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"); 
	} 
 
} 
 
</pre>
<p><strong>ClientBusinessService.java</strong></p>
<pre class="highlight">/** 
 * 
 */ 
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"); 
	} 
 
} 
 
</pre>
<h3>Step 3: Let&#8217;s create a context class i.e. InitialContext for JNDI lookup</h3>
<p><strong>InitialContext.java</strong></p>
<pre class="highlight">/** 
 * 
 */ 
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;			 
	} 
} 
 
</pre>
<h3>Step 4: Let&#8217;s create a services cache class.</h3>
<p><strong>ServicesCache.java</strong></p>
<pre class="highlight">/** 
 * 
 */ 
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); 
		} 
	} 
} 
 
</pre>
<h3>Step 5: Let&#8217;s create Service Locator</h3>
<p><strong>ServiceLocator.java</strong></p>
<pre class="highlight">/** 
 * 
 */ 
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; 
	 } 
} 
 
</pre>
<h3>Step 6: Let&#8217;s create a demo class that use ServiceLocator to demonstrate Service Locator Design Pattern.</h3>
<p><strong>ServiceLocatorPatternDemo.java</strong></p>
<pre class="highlight">/** 
 * 
 */ 
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();	 
	} 
 
} 
 
</pre>
<h3>Step 7: Let&#8217;s run this demo class and verify the output.</h3>
<pre class="highlight">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 
 
</pre>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/business-delegate/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/session-facade/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '4053'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…