|
|
|
|
|
by johnyzee
5462 days ago
|
|
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. |
|
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();
}