博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Tuscany SCA Core实现的SPI机制
阅读量:2395 次
发布时间:2019-05-10

本文共 1862 字,大约阅读时间需要 6 分钟。

参考:[url]http://kevinkevin1979.iteye.com/blog/837715[/url]
SPI的全名为Service Provider Interface.普通开发人员可能不熟悉,因为这个是针对厂商或者插件的。在java.util.ServiceLoader的文档里有比较详细的介绍。究其思想,其实是和"Callback"差不多。“Callback”的思想是在我们调用API的时候,我们可以自己写一段逻辑代码,传入到API里面,API内部在合适的时候会调用它,从而实现某种程度的“定制”。
典型的是Collections.sort(List<T> list,Comparator<? super T> c)这个方法,它的第二个参数是一个实现Comparator接口的实例。我们可以根据自己的排序规则写一个类,实现此接口,传入此方法,那么这个方法就会根据我们的规则对list进行排序。
把这个思想扩展开来,我们用SPI来重新实现上面的例子。客户把自己的排序规则写成一个类,并且打包归档成Jar文件,这个Jar文件里面必须有META-INF目录,其下又有services目录,其下有一个文本文件,文件名即为接口的全名:java.util.Comparator。
--META-INF
--services
--java.util.Comparator
文件内容只有一行:
com.ruijie.ComparatorProvider
这一行是你实现了Comparator接口的类的全名,它的代码如下:
package com.ruijie;   import java.util.Comparator;   import com.mycompany.myapp.MyItem;   public class ComparatorProvider implements Comparator
{ @Override public int compare(MyItem o1, MyItem o2) { //依据name排序 return o1.getName().compareTo(o2.getName()); } }
编译打包后,把它放到你的主程序的class path里。下面是你的主程序:
//从class path中所有Jar的META-INF目录中搜索,找到合适的类并加载。   private static ServiceLoader
serviceLoader = ServiceLoader.load(Comparator.class); public static void main(String[] args) { List
myList = new ArrayList
(); myList.add(new MyItem(2,"c","hhh")); myList.add(new MyItem(3,"k","ooo")); myList.add(new MyItem(4,"d","ppp")); myList.add(new MyItem(5,"b","ggg")); showList(myList); Collections.sort(myList,getCompartor()); showList(myList); } @SuppressWarnings("unchecked") private static Comparator
getCompartor() { for(Comparator service : serviceLoader) { return (Comparator
)service; } return null; }
要注意的是serviceLoader开始只是加载类,实例化要到第一次用的时候。类MyItem和方法showList并不重要,所以你不必在意。你可以按照这个规则,写另外一个排序规则的Jar,随时可以更换你的排序规则.

转载地址:http://hnwob.baihongyu.com/

你可能感兴趣的文章
深度学习 vs. 概率图模型 vs. 逻辑学
查看>>
IDL box plot
查看>>
IDL vector filed plot
查看>>
piecewise constant function 阶跃常函数
查看>>
IDL save postscript file
查看>>
Bibtex如何使authors in the citation 最多显示两个
查看>>
Bibtex 如何cite 不同格式
查看>>
Cmake environmental variables: how to make find_package, find_path and find_library work
查看>>
Cmake space in path windows
查看>>
Differences between Tesla and a GeForce Series GPU
查看>>
Faster Parallel Reductions on Kepler
查看>>
NVIDIA Tesla C2075 vs Tesla K10 theoretical performance
查看>>
Fast floor/ceiling functions C
查看>>
Continue Long Statements on Multiple Lines Matlab
查看>>
What does “warning: not all control paths return a value” mean? (C++)
查看>>
C++ 运算符优先级
查看>>
Savitzky-Golay smoothing
查看>>
IDL get variable size in bytes
查看>>
high-frequency emphasis filter matlab
查看>>
cat -n
查看>>