对于全局只有一个实例,且需要在多个模块访问的类如何实现,使用普通的单例模式还是使用Service,二者都有缺点,还是下面的全局服务的模式比较好。
————————————————————————————————————————————————————————————————————
Global services—i.e., services that can be used by multiple modules and that are only provided
by one module—are typically implemented using abstract (singleton) classes. With this
pattern, the services manage the implementation on their own and provide an additional
trivial implementation (as an inner class) in case there is no other implementation registered
in the system. This has the advantage that the user always gets a valid reference to a service and
never a null value.
An example would be an MP3 player service (see Listing 6-3) used by different
modules—e.g., a search list or playlist. The implementation of the player is exchangeable.
Listing 6-3. MP3 player as a global service in the MP3 Services module
public abstract void play(Mp3FileObject mp3);
public abstract void stop();
public static Mp3Player getDefault() {
Mp3Player player = Lookup.getDefault().lookup(Mp3Player.class);
if(player == null) {
player = new DefaultMp3Player();
}
return(player);
}
private static class DefaultMp3Player extends Mp3Player {
public void play(Mp3FileObject mp3) {
// send file to an external player or
// provide own player implementation or
// show a message that no player is available
}
public void stop() {}
}
}
public void play(Mp3FileObject mp3) {
// play file
}
public void stop() {
// stop player
}
}
IOProvider. The class IOProvider grants access to the Output window. The service provider
actually writing the data to the Output window is in a separate class, NbIOProvider, in a separate
module. If the module is available and the service provider registered, its implementation
is retrieved via the static method IOProvider.getDefault(). If the module is not available, the
default implementation is provided, which writes the output data to the default output
(System.out and System.err).