zoukankan      html  css  js  c++  java
  • 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).

  • 相关阅读:
    java中锁的应用(ReentrantLock)
    java中锁的应用(synchronized)
    Redis + keepalived 主从设置与搭建
    Smokeping搭建
    Mysql5.7双主安装与使用
    软件测试作业3
    软件测试作业2
    github&文章
    PICT的安装和使用
    Junit的安装和使用
  • 原文地址:https://www.cnblogs.com/cuizhf/p/2195071.html
Copyright © 2011-2022 走看看