我是靠谱客的博主 含蓄奇异果,这篇文章主要介绍设计模式-静态工厂之服务提供者框架,现在分享给大家,希望可以做个参考。


一、服务提供者框架组件

服务提供者有以下几个组件:

1、服务接口,这是提供者实现的;

2、提供者注册API,这是系统用来注册实现,让客户端访问;

3、服务访问API,这是客户端用来获取服务的实例;

4、服务提供者接口,这是提供者负责创建其服务实现的实例;

二、服务提供者框架简单实现


复制代码
1
2
3
4
//服务接口 public Interface Service { public abstract serve(); }

复制代码
1
2
3
4
//服务提供者接口 public Interface Provider { Service newService(); }


复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//Noninstantiable class for service registration and access public class Services { private Services() {}; //Maps service name to services private static final Map<String,Provider> providers = new ConcurrentHashMap<String,Provider>(); public static final String DEFAULT_PROVIDER_NAME = "<def>"; //Provider registration API public static void registerDefaultProvider(Provider p) { registerProvider(DEFAULT_PROVIDER_NAME,p); } public static void registerProvider(String name, Provider p) { providers.put(name,p); } //Service access API public static Service newInstance() { return newInstance(DEFAULT_PROVIDER_NAME); } public static Service newInstance(String name) { Provider p = providers.get(name); if(p == null) { throw new IllegalArgumentException("No provider registered with name: " + name); } return p.newService(); } }

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//服务提供者接口 public class EntityProvider implements Provider {     static{         ServiceManager.registerService("EntityService", new EntityProvider());     }          @override     protect void newService() {         return new ServiceImpl();     }          class ServiceImpl implements Service {              @override         protected void serve() {             System.out.println("service that entity provided serve");         }              }      }

复制代码
1
2
3
4
5
6
7
8
9
10
11
//测试 public class Test { public static void main(String[] args) { Service s = Services.newInstance("EntityService"); s.serve(); } }





最后

以上就是含蓄奇异果最近收集整理的关于设计模式-静态工厂之服务提供者框架的全部内容,更多相关设计模式-静态工厂之服务提供者框架内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(54)

评论列表共有 0 条评论

立即
投稿
返回
顶部