Composition of the service provider framework
Service Interface-the service provider implements this interface
Provider registration API-the system is used to register the implementation and provide client access
Service access API -- used by the client to obtain the service instance
Service Provider Interface
The general process is that if a client needs a service, it is necessary to implement the service, and the service is implemented by its provider!
For customers to get different implementations of the same service, we usually get this service through a service manager. The Service Manager is like a big manager,
Your usual situation is to tell the butler that I want to prepare the service provided by xxx, and then the butler finds it in his own books to find the provider with the name you said.
Once the provider is found, the provider will send this service to the butler, and the butler will give it to you!
Generally, the provider registers itself to the butler.
[Java]
Package com. baobaoyeye. test. psapi;
Public interface Service {
Public String read ();
Public void write (String arg );
}
[Java]
Package com. baobaoyeye. test. psapi;
Public interface Provider {
Public Service getService ();
}
[Java]
Package com. baobaoyeye. test. psapi;
Import java. util. concurrent. ConcurrentHashMap;
Public class ServiceManager {
Private ServiceManager (){}
Private static final ConcurrentHashMap <String, Provider> providers =
New ConcurrentHashMap <String, Provider> ();
Public static void registerService (String name, Provider provider ){
Providers. put (name, provider );
}
Public static Service getService (String name ){
Provider p = providers. get (name );
If (p! = Null ){
Return p. getService ();
}
Return null;
}
}
[Java]
Package com. baobaoyeye. test. psapi. impl;
Import com. baobaoyeye. test. psapi. Provider;
Import com. baobaoyeye. test. psapi. Service;
Import com. baobaoyeye. test. psapi. ServiceManager;
Public class TestProvider implements Provider {
Static {
ServiceManager. registerService ("TestService", new TestProvider ());
}
@ Override
Public Service getService (){
Return new ServiceImpl ();
}
Class ServiceImpl implements Service {
Private String tmp;
@ Override
Public String read (){
Return this. tmp;
}
@ Override
Public void write (String arg ){
This. tmp = arg;
}
}
}
[Java]
Package com. baobaoyeye. test. psapi;
Public class Test {
/**
* @ Param args
*/
Public static void main (String [] args ){
Try {www.2cto.com
Class. forName ("com. baobaoyeye. test. psapi. impl. TestProvider ");
Service s = ServiceManager. getService ("TestService ");
S. write ("hahaha ");
System. out. println (s. read ());
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
}
}
}
Author: baobaoyeye