Lee Ching-Chan
Lee Ching-Chan

Reputation: 35

Inherit from a singleton pattern

I've got a problem while I'm trying to inherit a class which is followed by Singleton Pattern. Suppose there is a class, known as P, followed by Singleton Pattern and implementing an interface known as I_able.

abstract class P implement I_able {
    static protected I_able instance = null; 
    protected object member1;

    // abstract static I_able getInstance(); <-- this is an illegal declaration.

    abstract public void method1() ;
} // class P

Now, there are two class wanting to inherit from P as following.

class A inheritance P {
    static public I_able getInstance() {
        if ( instance == null ) 
             instance = new A() ;
        return (A) instance ;
    } // getInstance()

    override public void method1() {
        ...
    } // method1() 
} // A()

class B inheritance P {
    static public I_able getInstance() {
        if ( instance == null ) 
            instance = new B() ;
        return (B) instance ;
    } // getInstance()

    override public void method1() {
        ...
    } // method1() 
} // B()

The problem is why the instance in A and instance in B are the same object. Actually, I kind of know why is that but I'm wondering how can I fix that. A and B must be the one and only object in the program. Any suggestion ?

Upvotes: 3

Views: 96

Answers (1)

James Maa
James Maa

Reputation: 1794

The problem in your code is your static I_able instance is defined in your parent class P.

Thus, when you getInstancein class A and B, they would both reference to their parent's class P's static variable instance.

I don't know a lot how you exactly want your function to execute, but one suggested edit here would be implement Singleton pattern in each of the children class.

class A inheritance P {
    static protected I_able AInstance = null; 

    static public I_able getInstance() {
        if ( AInstance == null ) 
             AInstance = new A() ;
        return (A) AInstance ;
    } // getInstance()

    override public void method1() {
        ...
    } // method1() 
} // A()

class B inheritance P {
    static protected I_able BInstance = null; 

    static public I_able getInstance() {
        if ( BInstance == null ) 
            BInstance = new B() ;
        return (B) BInstance ;
    } // getInstance()

    override public void method1() {
        ...
    } // method1() 
} // B()

Upvotes: 1

Related Questions