静态工厂方法返回的对象所属的类,在编写包含该静态工厂方法的类时可以不必存在。这种灵活的静态工厂方法构成了服务提供者框架(Service Provider Framework)的基础,例如JDBC API。
服务提供者框架中有三个重要的组件:服务接口(Sevice Interface),这是提供者实现的;提供者注册API(provider Registration API),这是系统用来注册实现的;服务访问API,是客户端用来获取服务的实例。
JDBC源代码学习之服务提供者框架
http://edwinljg.iteye.com/blog/565742
package chapter2;
/*
* 服务接口。<BR>
*/
public interface Service {
public String read();
public void write(String content);
}
package chapter2;
/*
* 服务提供者接口。<BR>
*/
public interface Provider {
public Service getService();
}
package chapter2;
/*
* 服务提供者实现。<BR>
*/
public class AdobeProvider implements Provider {
static {
ServiceManager.registerProvider("Adobe", new AdobeProvider());
System.out.println("12313");
}
public Service getService() {
return new ServiceImpl();
}
class ServiceImpl implements Service {
public String read(){
System.out.println("Adobe read...");
return "";
}
public void write(String content) {
System.out.println("Adobe write...");
}
}
}
package chapter2;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 服务管理类。<BR>
*/
public class ServiceManager {
private ServiceManager() {
}
private static final Map<String, Provider> providers =
new ConcurrentHashMap<String, Provider>();
public static void registerProvider(String name, Provider p) {
providers.put(name, p);
}
public static Service getService(String name) {
Provider p = providers.get(name);
if(p == null) {
throw new IllegalArgumentException("No provider registered with name:" + name);
}
return p.getService();
}
}
package chapter2;
/**
* 测试用类。<BR>
*/
public class Test {
public static void main(String []args) throws Exception {
//註冊服务
Class.forName("chapter2.AdobeProvider");
//Class.forName("MicrosoftProvider");
//Class.forName("MacProvider");
//获得服务
Service service = ServiceManager.getService("Adobe");
//Service service = ServiceManager.getService("Microsoft");
//Service service = ServiceManager.getService("Mac");
service.read();
service.write("title");
}
}
对于JDBC来说,Connction就是它的服务访问接口,DriverManagers是提供者注册ApI,DriverManager.getConnetion是服务访问API.Driver就是服务提供者接口。