Service Provider Interface
解耦,主程序和实现类之间不用硬编码
package com.mousycoder.mycode.thinking_in_jvm; /** * @version 1.0 * @author: mousycoder * @date: 2019-09-16 16:14 */ public interface SPIService { void execute(); }
package com.mousycoder.mycode.thinking_in_jvm; /** * @version 1.0 * @author: mousycoder * @date: 2019-09-16 16:16 */ public class SpiImpl1 implements SPIService { @Override public void execute() { System.out.println("SpiImpl1.execute()"); } }
package com.mousycoder.mycode.thinking_in_jvm; /** * @version 1.0 * @author: mousycoder * @date: 2019-09-16 16:16 */ public class SpiImpl2 implements SPIService { @Override public void execute() { System.out.println("SpiImpl2.execute()"); } }
在 resources/META-INF/services/目录下创建文件名为com.mousycoder.mycode.thinking_in_jvm.SPIService的文件,内容
com.mousycoder.mycode.thinking_in_jvm.SpiImpl1
com.mousycoder.mycode.thinking_in_jvm.SpiImpl2
主程序
package com.mousycoder.mycode.thinking_in_jvm; import sun.misc.Service; import java.util.Iterator; import java.util.ServiceLoader; /** * @version 1.0 * @author: mousycoder * @date: 2019-09-16 16:21 */ public class SPIMain { public static void main(String[] args) { Iterator<SPIService> providers = Service.providers(SPIService.class); ServiceLoader<SPIService> load = ServiceLoader.load(SPIService.class); while (providers.hasNext()){ SPIService ser = providers.next(); ser.execute(); } System.out.println("-----------------------"); Iterator<SPIService> iterator = load.iterator(); while (iterator.hasNext()){ SPIService ser = iterator.next(); ser.execute(); } } }
输出
SpiImpl1.execute() SpiImpl2.execute() ----------------------- SpiImpl1.execute() SpiImpl2.execute()