Extending singleton singleton inheritance
suggest changeIn this example, base class Singleton provides getMessage() method that returns "Hello world!" message.
Its subclasses UppercaseSingleton and LowercaseSingleton override getMessage() to change the message.
/*
Enumeration that represents possible classes of singleton instance.
If unknown, we'll go with base class - Singleton.
*/
enum SingletonKind {
UNKNOWN,
LOWERCASE,
UPPERCASE
}
//Base class
class Singleton{
/*
The subclasses are private inner classes, so other classes cannot extend them.
*/
private class UppercaseSingleton extends Singleton {
private UppercaseSingleton(){
super();
}
@Override
public String getMessage() {
return super.getMessage().toUpperCase();
}
}
//Another extended class.
private class LowercaseSingleton extends Singleton
{
private LowercaseSingleton(){
super();
}
@Override
public String getMessage() {
return super.getMessage().toLowerCase();
}
}
//Applying Singleton pattern
private static SingletonKind kind = SingletonKind.UNKNOWN;
private static volatile Singleton instance;
/*
By using this method prior to getInstance() method, you effectively change the
type of singleton instance to be created.
*/
public static synchronized void setKind(SingletonKind kind) {
Singleton.kind = kind;
}
/*
If needed, getInstance() creates an instance of the class selected by kind.
Call setKind before the first getInstance(); later calls keep the first instance.
*/
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
Singleton singleton = new Singleton();
switch (kind) {
case UNKNOWN:
instance = singleton;
break;
case LOWERCASE:
// new LowercaseSingleton() is illegal here: a non-static
// inner class needs an enclosing instance.
instance = singleton.new LowercaseSingleton();
break;
case UPPERCASE:
instance = singleton.new UppercaseSingleton();
break;
}
}
}
}
return instance;
}
//Singletons state that is to be used by subclasses
protected String message;
//Private constructor prevents external instantiation.
private Singleton()
{
message = "Hello world!";
}
//Singleton's API. Subclasses may override this.
public String getMessage() {
return message;
}
}
//Just a small test program
public class ExtendingSingletonExample {
public static void main(String args[]){
//just uncomment one of following lines to change singleton class
//Singleton.setKind(SingletonKind.UPPERCASE);
//Singleton.setKind(SingletonKind.LOWERCASE);
Singleton singleton = Singleton.getInstance();
System.out.println(singleton.getMessage());
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents