Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is extending a singleton class wrong?

I am creating a logger for an application. I am using a third party logger library. In which logger is implemented as singleton.

I extended that logger class because I want to add some more static functions. In these static functions I internally use the instance (which is single) of Logger(which i inherited).

I neither creates instance of MyLogger nor re-implemented the getInstance() method of super class. But I am still getting warnings like destructor of MyLogger can not be created as parent class (Loggger) destructor is not accessible.

I want to know, I am I doing something wrong? Inheriting the singleton is wrong or should be avoided??

like image 750
Anwar Shaikh Avatar asked Mar 26 '12 17:03

Anwar Shaikh


People also ask

Can singleton class be extended?

Hence, you can extend a singleton class only if you have a non-private constructor in the singleton class as shown in the code snippet given below. You can now extend the singleton class as shown below. Likewise, you cannot inherit a static class and override its methods.

What is wrong with singletons?

The most important drawback of the singleton pattern is sacrificing transparency for convenience. Consider the earlier example. Over time, you lose track of the objects that access the user object and, more importantly, the objects that modify its properties.

What is a common criticism of the singleton design?

Criticism. Critics consider the singleton to be an anti-pattern that introduces global state into an application, often unnecessarily. This introduces a potential dependency on the singleton in all code it is visible to, requiring analysis of implementation details to determine if a dependency actually exists.

What is one of the most common mistakes you can make when implementing a singleton?

A common mistake with that implementation is to neglect synchronization, which can lead to multiple instances of the singleton class.


2 Answers

Leaving the merits of singleton pattern aside (there is a school of thought that describes it as an anti-pattern) it should not be necessary to subclass it to simply add static functionality. Here are language-specific approaches that I would prefer to subclassing a singleton:

  • Use a free-standing function enclosed in a C++ namespace
  • Use an extension class in C#
  • Use a helper class in Java
  • Use a Category in Objective-C
like image 180
Sergey Kalinichenko Avatar answered Sep 18 '22 00:09

Sergey Kalinichenko


I would use a non-singleton and delegate calls to the singleton where needed. Whenever you have the opportunity to get rid of a Singleton, go for it.

like image 30
Garrett Hall Avatar answered Sep 19 '22 00:09

Garrett Hall