• Global Services


    下面这段内容来自《the definitive guide to netbeans platform》,回答了一个困扰我的问题:

     对于全局只有一个实例,且需要在多个模块访问的类如何实现,使用普通的单例模式还是使用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 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).

  • 相关阅读:
    vscode安装扩展插件提示:扩展不可用,XHR error?
    react函数组件的条件渲染和列表渲染
    动态设置背景图片和图片地址
    computed和watch,getters的计算变化
    VueLazyLoad图片懒加载
    vuex实现数据持久化
    vuex不需要一个个引入模块文件
    react的state和setState
    热爱生命 汪国真
    分分钟手写http server
  • 原文地址:https://www.cnblogs.com/cuizhf/p/2195071.html
Copyright © 2020-2023  润新知