Singleton with subclass in java

The most common way to implement singleton in java is to use a private constructor with a public access method in the form of -

public class Singleton { private static Singleton instance = null; private Singleton() { } public static synchronized Singleton getInstance(){ if (instance == null) { instance = new Singleton(); } return instance; } } 

However, since the constructor is private, it prevents the subclass of singleton. Is there a way we can do a singleton that allows subclasses?

+4
source share
3 answers

When you have class A extends B , instance A essentially "includes" instance B Thus, the concept of inheritance itself contradicts the singleton model.

Depending on what you need it for, I would consider using composition / delegation. (A will refer to a singleton, not an extension of its class). If for some reason you need inheritance, create an interface using the Singleton methods, use Singleton to implement this interface, and then another class also implements this interface and pass Singleton to implement the appropriate methods.

+6
source

If you can inherit it, it is not a very singleton, since each inherited class will have at least one instance.

However, you can simply create a protected constructor.

+9
source

Do you want to provide some inherited behavior for the singleton series? If so, perhaps you can move this code to an abstract class.

As Slacks noted, the singleton extension will no longer have a singleton character.

0
source

Source: https://habr.com/ru/post/1386893/


All Articles