Search code examples
singletonabstractvala

Vala: How to refer an abstract class' subclass?


Consider the following:

abstract class Singleton : Object {
    private static Singleton _instance = null;
    public static Singleton instance() {
        if (instance == null) {
            instance = // constructor call goes here
        }
        return instance;
    }
}

class Foo : Singleton {
    Foo() {}
}

var test = Foo.instance();

I would like to implement a singleton in an abstract class. My question is: How can I refer to the subclass constructor from Singleton.instance()?


Solution

  • Inheritance and the singleton pattern don't mix well:

    C++ Singleton class - inheritance good practice

    Why don't you just make your Foo class static (make all members static):

    public class Foo {
        // Static constructor
        public static Foo() {}
        // Static methods
        public static void bar () {}
        // Static attributes, etc.
    }
    

    This usually works as well. It does not work so well if your "singleton" has a costly construction and you want to avoid it being always constructed.