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.
Aucun commentaire:
Enregistrer un commentaire