Skip to main content

Changing source code at run-time with Service Locator pattern

I have a service to get some data but the result can be different basing on where the implementation is. Technically, I have two or more concrete implementation of an interface and I am able to switch using these concrete classes at run-time. That means I have a place to configure it without re-deploying the application. In order to overcome this issue, I use Service Locator design pattern and here I only care about two advantages below:
  • Encapsulating the specific implementation, we just declare the name and don't care about the implementation of the service.
  • Changing the implementation at run-time.

Client: an object that invokes the services via Service Locator
Business services: services that is used by Client.

Once again, I used the JFS Helloworld example from previous post for this example.

1. Create a service interface "CountryService" and two concrete classes "CountryService1" and "CountryService2" (Business services)

package vn.nvanhuong.servicelocator.service;

import java.util.List;

public interface CountryService{
 public List<String> getCountries();

The first concrete service:
package vn.nvanhuong.servicelocator.service.impl;

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

import vn.nvanhuong.servicelocator.service.CountryService;

public class CountryService1 implements CountryService{

 public List<String> getCountries() {
  List<String> result = new ArrayList<String>();
  return result;


The second concrete service:
package vn.nvanhuong.servicelocator.service.impl;

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

import vn.nvanhuong.servicelocator.service.CountryService;

public class CountryService2 implements CountryService{

 public List<String> getCountries() {
  List<String> result = new ArrayList<String>();
  return result;


2. Create class "InitialContext" that is used for looking up and creating classes basing on the provided names
package vn.nvanhuong.servicelocator;

import java.lang.reflect.Constructor;

public class IntitialContext {
 public Object lookup(String serviceName){
  if(serviceName != null){
   try {
    Class<?> clazz = Class.forName(serviceName);
    Constructor<?> ctor = clazz.getConstructor();
    Object object = ctor.newInstance();
    return object;
   } catch (Exception ex) {
  return null;


3. Create class "ServiceLocator", I used Singleton to cache the object.
package vn.nvanhuong.servicelocator;

public class ServiceLocator {
 private static ServiceLocator instance;
 private ServiceLocator(){}
 public static synchronized ServiceLocator getInstance(){
  if(instance == null){
   return new ServiceLocator();
  return instance;

 public Object getService(String serviceName) {
  IntitialContext initialContext = new IntitialContext();
  return initialContext.lookup(serviceName);


4. Create a resource file "" in order to configure the changing implementation at run-time. :)
country = vn.nvanhuong.servicelocator.service.impl.CountryService1
language = vn.nvanhuong.servicelocator.service.impl.LanguageService1

5. Calling SeviceLocator in Managed bean (Client)
package vn.nvanhuong.servicelocator.bean;

import java.util.List;
import java.util.Properties;

import javax.faces.bean.ManagedBean;

import vn.nvanhuong.servicelocator.ServiceLocator;
import vn.nvanhuong.servicelocator.service.CountryService;

@ManagedBean(name = "helloBean")
public class HelloBean {
 private List<String> countries;
 public HelloBean() throws IOException {
  Properties prop = new Properties();
     InputStream input = null;
     String filename = "";
  input = HelloBean.class.getClassLoader().getResourceAsStream(filename);

  CountryService countryService = (CountryService) ServiceLocator.getInstance()
        this.countries = countryService.getCountries();

 public List<String> getCountries() {
  return countries;

 public void setCountries(List<String> countries) {
  this.countries = countries;
6. GUI code: index.xhtml
<!DOCTYPE html>
<html xmlns=""
 <title>Service Locator</title>
 <h3>Lis of countries:</h3>
 <h:dataTable value="#{helloBean.countries}" var="country">
         <h:outputText value="#{country}" />


7. Test (on Tomcat v7.0)


Use the "CountryService1" by changing in "", don't need to restart the server.

country = vn.nvanhuong.servicelocator.service.impl.CountryService1

Use the "CountryService2" by changing in "", don't need to restart the server.

country = vn.nvanhuong.servicelocator.service.impl.CountryService2

Here we also can add more concrete classes of CountryService and just declare in file "" for using. For this reason, I use Java Reflection to create the objects basing on the provided names in general way otherwise we have to change the InitialContext whenever we want to add new concrete class of "CountryService".

There might have several ways to implement this pattern but the idea is general so that my example is only a case. We also can improve my implementation by using caching technique, see reference [3].



Popular posts from this blog

The 2017 Scrum Guide, and My Notes Scrum is not only designed for software development Scrum can be used for addressing any complex issues:
1. Research and identify viable markets, technologies, and product capabilities;
2. Develop products and enhancements;
3. Release products and enhancements, as frequently as many times per day;
4. Develop and sustain Cloud (online, secure, on-demand) and other operational environments for product use; and,
5. Sustain and renew products.
Scrum Values is a key factor for building trust and respect among team members The five values are:
1. Commitment
2. Courage
3. Focus
4. Openness
5. Respect
Daily Scrum's questions are more focused on inspection and adaption rather than the status 1. What did I do yesterday that helped the Development Team meet the Sprint Goal?
2. What will I do today to help the Development Team meet the Sprint Goal?
3. Do I see any impediment that prevents me or the Development Team from meeting the Sprint Goal?
Why Scrum still needs Scru…

Git Feature Branch Workflow

Motivator It's important for a team to have an agreement on how the changes of source code should be applied.
According to projects and teams size, we will define a workflow or select one from recommended workflows; the "Feature Branch Workflow" is a candidate.
What is it? - One branch "master" for main codebase
- Several separated branches for features development
Why should we care? - Be super simple and allow each developer works on a particular feature.
- A stable codebase (master) benefits for continuous integration (CI) environment
- Leverage "Pull request" for Code review
How it works? A lifecyle of a feature branch (usually created by a story)
1. Creator creates a new branch from a story.  For example: "ABC-1-setup-projects"
2. Creator checkouts the created branch and works on the branch (commits, pushes)
3. Creator has done the feature, he uses "pull request" to merge his branch into branch "master"
4. Reviewers…

How did I start practising BDD?

At the beginning days I has practised TDD (Test Driven Development) with using JUnit, I approached that I should test methods belong to a class. For example:

I have a class with some methods:

public class A{ public void method1(){ } public void method2(){ } }
And then, I wrote some test methods to check the corresponding ones, for example:

public class ATest{ @Test public void testMethod1(){ .... assertTrue(...); ..... assertEquals(...); } @Test public void testMethod2(){ } }
After that, I know that a test method (ex: testMethod1) should just only tests one thing, so I decided to write more methods for each cases. It looks like the following:

@Test public void testMethod1_When_Case1(){ .... assertTrue(...); } @Test public void testMethod1_When_Case2(){ .... assertEquals(...); }
However, it was not a really good approach because it seems that I just focused on test the functionality of the method of the class. With TDD approach, I knew that I should test the …

Styling Sort Icons Using Font Awesome for Primefaces' Data Table

So far, Primefaces has used image sprites for displaying the sort icons. This leads a problem if we want to make a different style for these icons; for example, I would make the icon "arrow up" more blurry at the first time table loading because I want to highlight the icon "arrow down". I found a way that I can replace these icons to Font Awesome icons.

We will use "CSS Pseudo-classes" to archive it. The hardest thing here is that we should handle displaying icons in different cases. There is a case both "arrow up" and "arrow down" showing and other case is only one of these icons is shown.

.ui-sortable-column-icon.ui-icon.ui-icon-carat-2-n-s { background-image: none; margin-left: 5px; font-size: 1.1666em; position: relative; } .ui-sortable-column-icon.ui-icon.ui-icon-carat-2-n-s:not(.ui-icon-triangle-1-s)::before { content: "\f106"; font-family: "FontAwesome"; position: absolute; t…

Coding Exercise, Episode 1

I have received the following exercise from an interviewer, he didn't give the name of the problem. Honestly, I have no idea how to solve this problem even I have tried to read it three times before. Since I used to be a person who always tells myself "I am not the one good at algorithms", but giving up something too soon which I feel that I didn't spend enough effort to overcome is not my way. Then, I have sticked on it for 24 hours.

According to the given image on the problem, I tried to get more clues by searching. Thanks to Google, I found a similar problem on Hackerrank (attached link below). My target here was trying my best to just understand the problem and was trying to solve it accordingly by the Editorial on Hackerrank. Due to this circumstance, it turns me to love solving algorithms from now on (laugh). Check it out!
Problem You are given a very organized square of size N (1-based index) and a list of S commands
The ith command will follow the format (a[…