设计模式简介
设计模式(Design pattern)代表了最佳的实践,通常被有经验的面向对象的软件开发人员所采用。设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案。这些解决方案是众多软件开发人员经过相当长的一段时间的试验和错误总结出来的。
设计模式是一套被反复使用的、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了重用代码、让代码更容易被他人理解、保证代码可靠性。 毫无疑问,设计模式于己于他人于系统都是多赢的,设计模式使代码编制真正工程化,设计模式是软件工程的基石,如同大厦的一块块砖石一样。项目中合理地运用设计模式可以完美地解决很多问题,每种模式在现实中都有相应的原理来与之对应,每种模式都描述了一个在我们周围不断重复发生的问题,以及该问题的核心解决方案,这也是设计模式能被广泛应用的原因。
服务定位器模式
服务定位器模式(Service Locator Pattern)用在我们想使用 JNDI 查询定位各种服务的时候。考虑到为某个服务查找 JNDI 的代价很高,服务定位器模式充分利用了缓存技术。在首次请求某个服务时,服务定位器在 JNDI 中查找服务,并缓存该服务对象。当再次请求相同的服务时,服务定位器会在它的缓存中查找,这样可以在很大程度上提高应用程序的性能。以下是这种设计模式的实体。
服务(Service) - 实际处理请求的服务。对这种服务的引用可以在 JNDI 服务器中查找到。
Context / 初始的 Context - JNDI Context 带有对要查找的服务的引用。
服务定位器(Service Locator) - 服务定位器是通过 JNDI 查找和缓存服务来获取服务的单点接触。
缓存(Cache) - 缓存存储服务的引用,以便复用它们。
客户端(Client) - Client 是通过 ServiceLocator 调用服务的对象。
实现

新建一个接口
public interface Service {
public void run();
public String getName();
}
实现这个接口
public class Service1 implements Service{
@Override
public void run() {
System.out.println("服务1已经启动");
}
public String getName() {
System.out.println("服务1");
return "服务1";
}
}
public class Service2 implements Service{
@Override
public void run() {
System.out.println("服务2已经启动");
}
public String getName() {
return "服务2";
}
}
适配
public class ServiceContext {
public Service getService(String serviceName) {
if("servrce1".equalsIgnoreCase(serviceName)) {
return new Service1();
}else {
return new Service2();
}
}
}
服务缓存
public class Cache {
public List<Service> list = new ArrayList<>();
public Service getService(String serviceName) {
for (Service service : list) {
if(service.getName().equalsIgnoreCase(serviceName)) {
//service.run();
return service;
}
}
return null;
}
public void addService(Service service) {
list.add(service);
}
}
定位器
public class Locator {
public static Cache cache;
static {cache = new Cache();}
public Service getService(String serviceName) {
Service service = cache.getService(serviceName);
if(service != null) {
System.out.println("缓存已生效");
return service;
}
Service service2 = new ServiceContext().getService(serviceName);
//System.out.println(service2.getName());
cache.addService(service2);
return service2;
}
}
运行
public static void main(String[] args) {
Locator locator = new Locator();
for (int i = 0; i < 3; i++) {
locator.getService("服务2").run();
System.out.println("==============");
}
}
服务2已经启动
==============
缓存已生效
服务2已经启动
==============
缓存已生效
服务2已经启动
==============
1404

被折叠的 条评论
为什么被折叠?



