forked from hacker85/JavaLessons
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServiceLocatorLesson.java
More file actions
73 lines (70 loc) · 1.87 KB
/
Copy pathServiceLocatorLesson.java
File metadata and controls
73 lines (70 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package patterns.web;
import java.util.ArrayList;
import java.util.List;
public class ServiceLocatorLesson {
public static void main(String[] args) {
Service service = ServiceLocator.getService("Service1");
service.execute();
service = ServiceLocator.getService("Service2");
service.execute();
}
}
interface Service {
String getName();
void execute();
}
class Service1 implements Service {
public void execute(){
System.out.println("Executing Service1");
}
@Override
public String getName() {
return "Service1";
}
}
class Service2 implements Service {
public void execute(){
System.out.println("Executing Service2");
}
@Override
public String getName() {
return "Service2";
}
}
class InitialContext {
public Object lookup(String jndiName){
if(jndiName.equalsIgnoreCase("SERVICE1")){
return new Service1();
}else if (jndiName.equalsIgnoreCase("SERVICE2")){
return new Service2();
}
return null;
}
}
class Cache {
private List<Service> services = new ArrayList<>();
public Service getService(String serviceName){
for (Service service : services) {
if(service.getName().equalsIgnoreCase(serviceName)){
return service;
}
}
return null;
}
public void addService(Service newService){
services.add(newService);
}
}
class ServiceLocator {
private static Cache cache = new Cache();
public static Service getService(String jndiName){
Service service = cache.getService(jndiName);
if(service != null){
return service;
}
InitialContext context = new InitialContext();
Service service1 = (Service)context.lookup(jndiName);
cache.addService(service1);
return service1;
}
}