Click here to Skip to main content
15,891,833 members
Articles / All Topics

A Less Evil Singleton

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
22 Jul 2011LGPL31 min read 9.7K   4   1
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.

This article was originally posted at http://blog.gauffin.org/2011/07/a-less-evil-singleton

License

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


Written By
Founder 1TCompany AB
Sweden Sweden

Comments and Discussions

 
Question! can't fault this technique Pin
EbenRoux25-Jul-11 18:42
EbenRoux25-Jul-11 18:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.