service locator pattern

This commit is contained in:
mherbaghinyan 2018-04-20 10:11:59 +04:00
parent ce5113c48c
commit 78a6c223eb
7 changed files with 132 additions and 0 deletions

View File

@ -0,0 +1,39 @@
package com.baeldung.designpatterns.service.locator;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Gebruiker on 4/20/2018.
*/
public class Cache {
private List<MessagingService> services;
public Cache(){
services = new ArrayList<MessagingService>();
}
public MessagingService getService(String serviceName){
for (MessagingService service : services) {
if(service.getServiceName().equalsIgnoreCase(serviceName)){
System.out.println("Returning cached " + serviceName + " object");
return service;
}
}
return null;
}
public void addService(MessagingService newService){
boolean exists = false;
for (MessagingService service : services) {
if(service.getServiceName().equalsIgnoreCase(newService.getServiceName())){
exists = true;
}
}
if(!exists){
services.add(newService);
}
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.designpatterns.service.locator;
/**
* Created by Gebruiker on 4/20/2018.
*/
public class EmailService implements MessagingService {
public String getMessageBody() {
return "email message";
}
public String getServiceName() {
return "EmailService";
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.designpatterns.service.locator;
/**
* Created by Gebruiker on 4/20/2018.
*/
public class InitialContext {
public Object lookup(String jndiName) {
if (jndiName.equalsIgnoreCase("EmailService")) {
return new EmailService();
} else if (jndiName.equalsIgnoreCase("SMSService")) {
return new SMSService();
}
return null;
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.designpatterns.service.locator;
/**
* Created by Gebruiker on 4/20/2018.
*/
public class Main {
public static void main(String[] args) {
MessagingService service = ServiceLocator.getService("EmailService");
service.getMessageBody();
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.designpatterns.service.locator;
public interface MessagingService {
String getMessageBody();
String getServiceName();
}

View File

@ -0,0 +1,15 @@
package com.baeldung.designpatterns.service.locator;
/**
* Created by Gebruiker on 4/20/2018.
*/
public class SMSService implements MessagingService {
public String getMessageBody() {
return "sms message";
}
public String getServiceName() {
return "SMSService";
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.designpatterns.service.locator;
/**
* Created by Gebruiker on 4/20/2018.
*/
public class ServiceLocator {
private static Cache cache;
static {
cache = new Cache();
}
public static MessagingService getService(String jndiName){
MessagingService service = cache.getService(jndiName);
if(service != null){
return service;
}
InitialContext context = new InitialContext();
MessagingService service1 = (MessagingService)context.lookup(jndiName);
cache.addService(service1);
return service1;
}
}