Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: singleton from base class

Lets assume we've got base class:

public class Base {
      public Base(int i) {
      /* ... */
      }
      /* ... */
}

We want to create singleton based on this class. The problem is that class have public constructor, so extending it will result in singleton having public constructor, too:

public class SingletonBase extends Base {
   private static final SingletonBase _instance = new SingletonBase();

   private SingletonBase() {
      super(0);
   }

  public SingletonBase(int i) {  // Want to avoid this!
     super(i) 
  }

  public static void getInstance() {
     return _instance;
  }
  /* ... */       
}

Singleton, of course, cannot have public constructors, so we want to avoid this. So, what is most elegant way/pattern to have proper Singleton with functionalities from class Base?

Edit: Modifying Base class is prohibited, since it is from an external library.

like image 870
Kao Avatar asked Dec 03 '25 05:12

Kao


1 Answers

Constructors are not inherited. So just
delete this part and you'll get what you need.

public SingletonBase(int i) {  // Want to avoid this!
    super(i) 
}

Additionally, you may want to make the Base class
abstract so that no one can instantiate it by mistake
by calling the Base constructor directly.

public abstract class Base {
    public Base(int i) {
        /* ... */
    }
    /* ... */
}

public class SingletonBase extends Base {
    private static final SingletonBase _instance = new SingletonBase();

    private SingletonBase() {
        super(0);
    }

    public static SingletonBase getInstance() {
        return _instance;
    }
    /* ... */
}
like image 97
peter.petrov Avatar answered Dec 05 '25 21:12

peter.petrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!