Hacker News new | past | comments | ask | show | jobs | submit login

Not thread safe.



Thread safety is the same whether you use a static instance or plain static methods. In fact with all static members you don't have to worry about synchronizing initialization of the singleton object which is often done wrong.

The only reason to use a singleton over static members is that it feels like OO. I suppose it also makes it easier to replace the singleton with a 'multiton' at some point in the future which somewhat justifies it.


There isn't a clean way to initialize all of your static properties doing it that way. If you're using a language that has accessors you can call a private init method, but you have to do it for all of the properties. Or you can just use methods, but again you have to remember to call init at the beginning of them all. Or you could have a public init() and just remember to call it when your application first launches. Using a singleton is a natural way to have an entry point towards initialization. You can also have the best of both worlds by using static properties/methods that point to the singleton version.

In Java/C# you can use a nested class to ensure thread safety and cheat towards having your static methods. For example:

private int Foo() { }

public static int Foo() { return _instance.Foo(); }

private static FooBar _instance { return Nested.instance; }

FooBar() { // Initialize here! }

class Nested {

static Nested() { }

internal static readonly FooBar instance = new FooBar();

}




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: