must a subclass of a singleton class be a singleton class?

96 views Asked by At

According to Design Pattern by Gang of Four, a singleton class can have a subclass.

Must a subclass of a singleton class be a singleton class?

Can a singleton class have any number of subclasses?

Thanks.

2

There are 2 answers

2
Samuel Neff On

If a singleton had a subclass then it seems it would likely violate the purpose of a singleton. How can there be just one if there is a parent and child?

The one time I've used inheritance with a singleton is when the parent is an abstract class that provides very generic functionality to multiple singletons. Each child class is itself a singleton with one instances, and the parent is abstract with zero instances.

1
Wyman.lyu On

it's no problem, a singleton class can have a subclass.

class singleClass {
    ...
    getSingleton() // you can get singleton obj by this structure func
    ...
}

class subClass : singleClass {
    ...
   override getSingleton() // you can get sub singleton obj by this structure func
    subClass() // new obj
    ...
}

It is recommended that the same interface of the single instance be obtained