服务提供者框架示例

来源:互联网 发布:数码兽数据库 编辑:程序博客网 时间:2024/05/01 14:35

概念

静态工程方法返回的对象所属的类,在编写包含该静态工厂方法的类时可以不必存在。这种灵活的静态工厂方法构成了服务提供者框架(Service Provider Framework)的基础,例如JDBC(Java 数据库链接,Java Database Connectivity)API。服务提供者框架是指这样一个系统:多个服务提供者实现一个服务,系统为服务提供者的客户端提供多个实现,并把他们从多个实现中解耦出来。

组件

服务提供者框架中有三个重要的组件:
1. 服务接口(Service Interface),这是提供者实现的;
2. 提供者注册API(Provider Registration API),这是系统用来注册实现,让客户端访问它们的;
3. 服务访问API(Service Access API),是客户端用来获取服务的实例的。

服务访问API一般允许但是不要求客户端指定某种选择提供者的条件。如果没有这样的规定,API就会返回默认实现的一个实例。服务访问API是“灵活的静态工厂”,它构成了服务提供者框架的基础。

服务提供者框架的第四个组件是可选的:服务提供者接口(Service Provider Interface),这些提供者负责创建其服务实现的实例。如果没有服务提供者接口,实现就按照类名称注册,并通过反射方式进行实例化。

对于JDBC来说,Connection就是它的服务接口,DriverManager.registerDriver是提供者注册API,DriverManager.getConnection是服务访问API,Driver就是服务提供者接口。

示例

服务接口

public interface ServiceInterface {    void serve();}

服务接口实现

public class ServiceInterfaceImpl implements ServiceInterface {    @Override    public void serve() {        System.out.println("This is ServiceInterfaceImpl");    }}

服务管理类

  1. 提供者注册API
  2. 服务访问API
//Noninstantiable class for service registration and accesspublic class ServiceManager {    //Prevents instantiation    private ServiceManager() {    }    //Maps service names to services    private static final Map<String, Provider> providers = new ConcurrentHashMap<>();    public static final String DEFAULT_PROVIDER_NAME = "def";    //Provider registration API    public static void registDefaultProvider(Provider p) {        registProvider(DEFAULT_PROVIDER_NAME, p);    }    public static void registProvider(String name, Provider p) {        providers.put(name, p);    }    //ServiceInterface access API    public static ServiceInterface newInstance() {        return newInstance(DEFAULT_PROVIDER_NAME);    }    public static ServiceInterface newInstance(String name) {        Provider p = providers.get(name);        if (null == p) {            throw new IllegalArgumentException("No provider registered with name " + name);        }        return p.newService();    }}

服务提供者

public interface ServiceProvider {    ServiceInterface newService();}

服务提供者接口实现

public class EntityProvider implements ServiceProvider {    static {        ServiceManager.registProvider("ServiceInterfaceImpl",new EntityProvider());    }    @Override    public ServiceInterface newService() {        return new ServiceImpl();    }}

客户端类

public class Client {    public static void main(String[] args) throws ClassNotFoundException {        //实例化提供者实现类,并注册服务    Class.forName("org.wuxinshui.boosters.framework.ServiceProviderFramework.EntityProvider");        ServiceInterface service = ServiceManager.newInstance("ServiceInterfaceImpl");        service.serve();    }}

参考:Effective java 中文版(第2版)

0 0
原创粉丝点击