对于全局只有一个实例,且需要在多个模块访问的类如何实现,使用普通的单例模式还是使用Service,二者都有缺点,还是下面的全局服务的模式比较好。
————————————————————————————————————————————————————————————————————
Global services—i.e., services that can be used by multiple modules and that are only providedby one module—are typically implemented using abstract (singleton) classes. With thispattern, the services manage the implementation on their own and provide an additionaltrivial implementation (as an inner class) in case there is no other implementation registeredin the system. This has the advantage that the user always gets a valid reference to a service andnever a null value.An example would be an MP3 player service (see Listing 6-3) used by differentmodules—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 class Mp3Player { 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() {} } }Listing 6-4. MP3 player service provider in the MP3 Player module
public class MyMp3Player extends Mp3Player { public void play(Mp3FileObject mp3) { // play file } public void stop() { // stop player } }
Good examples for global services inside the NetBeans Platform are StatusDisplayer and 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).
转载于:https://www.cnblogs.com/cuizhf/archive/2011/09/29/2195071.html
相关资源:SAP GTS100 (SAP Global Trade Services)