简体   繁体   中英

How to reuse Singleton pattern?

When I want to reuse a Singleton pattern by using inheriting in Java language, something interesting confused me. I want share with you and ask you for a solution to reuse Singleton. My code is below.

// Singleton.java
public class Singleton {
    private static Singleton mSingletonInstance;

    protected Singleton() {
        System.out.println("New Singleton Instance.");
    }

    public static Singleton getInstance() {
        if (mSingletonInstance == null)
            mSingletonInstance = new Singleton();

        return mSingletonInstance;
    }
}


// ExtendedSingleton.java
public class ExtendedSingleton extends Singleton{

    private static ExtendedSingleton mExtendedSingleton;

    private ExtendedSingleton() {
        super();
        System.out.println("New Extended Singleton Instance.");
    }

    public static ExtendedSingleton getInstance() {
        if (mExtendedSingleton == null)
            mExtendedSingleton = new ExtendedSingleton();
        return mExtendedSingleton;
    }

    public static void main(String args[]) {
        ExtendedSingleton extendedSingleton = ExtendedSingleton.getInstance();
    }
}

Of course, I can run these code without any exception. But my intention is to reuse the Singleton pattern by extending a Singleton base class. However, I have to retype all of the code in the subclass and I didn't reuse anything at all, which is even not better that write a separate Singleton class whenever I need it. I am really confused. Could anyone show me how to reuse the Singleton pattern. Feel free to fix my English, which I know I must have a lot of mistakes.

I would just use an enum if you want to use the features of Java. Your classes would look like

enum Singleton {
    INSTANCE;
    // add fields and methods to taste
}

enum ExtendedSingleton {
    INSTANCE;
    // delegate to Singleton as required.
}

If you need inheritance, you can use an interface which they both implement.

Singleton pattern assumes a private constructor. You break this rule this is why the confusion. Do not extend it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM