domingo, septiembre 05, 2004

Patterns and .Net framework

I was watching some saved webcasts, and i found this one - Pattern Based Development for the Enterprise - presented by Craig Utley.

Well, this webcast is about three design patterns: singleton, factory and observer, and I remembered that a few time ago I didn´t know how .Net framework take care about singleton implementation, and maybe you don´t either, so here you have my .notes =)

As you probably know, Singleton pattern solve the need to have a single instance of a particular object (or a specific maximum number of objects).

There are some approaches, like this classical GOF implementation (using Double-Check Lock in multithreading applications):


class Singleton 
{
    public static Singleton Instance() {
        if (_instance == null) {
            lock (typeof(Singleton)) {
                if (_instance == null) {
                    _instance = new Singleton();
                }
            }
        }
        return _instance;      
    }
    protected Singleton() {}
    private static volatile Singleton _instance = null;
}


... and here you have the .Net Fx simplified version:

sealed class Singleton 
{
    private Singleton() {}
    public static readonly Singleton Instance = new Singleton();
}


worried about lazy initialization?, well, .Net Fx takes care about this during JIT process, it will initialize the Instance property when any method uses it. In other words, the class get constructed and instantiated when any static member of the class is used. By the other hand, .Net Fx addresses thread-safe initialization too. the framework internally guarantees thread safety on static type initialization.




No hay comentarios: