Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

A Less Evil Singleton

5.00/5 (1 vote)
22 Jul 2011LGPL31 min read 9.9K  
Wrap a singleton in a facade to make it less evil.

I’ve been working a bit more with my Griffin Framework and I’m almost ready to release the Specification library in it. The specification library is an abstraction layer similar to CommonLog and CommonServiceLocator although it contains alternatives to both of them and a bit more.

When I designed the logging interfaces I did decide to use sort of an singleton (LogManager) to be able to get a logger in each class that needs one. Since logging is such a core functionality and also well defined, I didn’t see a reason to use a regular service interface which could be used in the constructor (inversion of control). IMHO, it would only clutter all constructors since most classes will be using a logger.

The singleton facade works best for small classes that most likely will not be changed. My LogManager looks like this (comments and code contracts have been removed):

C#
public class LogManager
    {
        private static ILogManager _logManager = new NullLogManager();

        public static void Assign(ILogManager logManager)
        {
            _logManager = logManager;
        }

        public static ILogger GetLogger(Type type)
        {
            return _logManager.GetLogger(type);
        }

        public static ILogger GetLogger<T>()
        {
            return _logManager.GetLogger(typeof (T));
        }
    }

By using this approach, all users can easily get a logger while the implementors have a lot of flexibility to generate the ILogManager which is used by the facade. The logging abstraction layer actually does not care about how the ILogManager is created or configured. It’s an implementation detail only known by the user of the actual logging framework.

I do not recommend anyone to use a singleton facade unless it’s absolutely required. Usually, it should only be used in frameworks, your own internal one or one like this.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)