在Java中扩展单例

时间:2013-04-29 02:23:09

标签: java singleton

我想做的就是创建一个类,当你扩展它时,你会自动获得getInstance类。问题是,当我扩展它时,我不能引用子类。我能看到的唯一方法是通过类型转换((ClassName)class.getInstance()),但它不是非常用户友好。有什么建议吗?

2 个答案:

答案 0 :(得分:7)

你不能扩展一个合适的Singleton,因为它应该有一个私有的构造函数:

有效的Java项目2:使用私有构造函数强制执行单例属性

答案 1 :(得分:3)

覆盖单例的唯一方法是使用一个期望被覆盖的单例。最简单的方法是提供Singleton,它实现interface(或完全abstract本身),在首次使用getInstance()时内部实例化注入的单例。

public interface SingletonMethods // use a better name
{
    String getName();

    void doSomething(Object something);
}

public class Singleton // use a better name
{
    private Singleton() { /* hidden constructor */ }

    public static SingletonMethods getInstance()
    {
        return SingletonContainer.INSTANCE;
    }

    /**
     * Thread safe container for instantiating a singleton without locking.
     */
    private static class SingletonContainer
    {
        public static final SingletonMethods INSTANCE;

        static
        {
            SingletonMethods singleton = null;
            // SPI load the type
            Iterator<SingletonMethods> loader =
                ServiceLoader.load(SingletonMethods.class).iterator();

            // alternatively, you could add priority to the interface, or
            //  load a builder than instantiates the singleton based on
            //  priority (if it's a heavy object)
            // then, you could loop through a bunch of SPI provided types
            //  and find the "highest" priority one
            if (loader.hasNext())
            {
                singleton = loader.next();
            }
            else
            {
                // the standard singleton to use if not overridden
                singleton = new DefaultSingletonMethods();
            }

            // remember singleton
            INSTANCE = singleton;
        }
    }
}
相关问题