Özgür Belül

x += x++;
posts - 11, comments - 3, trackbacks - 0

Lazy Singleton

Singleton kalıbını doğru bir şekilde kullanmıyorsanız  class içerisinden sadece static method çağırsanız bile instance yaratmış olabilirsiniz. Belki de hiç kullanmayacağınız bu instance bellekte boşu boşuna yer işgal eder. Bu sorunu Singleton kalıbını lazy olarak tasarlarsanız aşabilirsiniz. Aşağıdaki gibi bir kullanımda construtorlara breakpoint koyup Singleton class'ı içerisinden MyMethod1()'i çağırdığınızda instance yaratılmadığını ancak metodun çağırılabilir olduğunu göreceksiniz. Instance sadece gerektiğinde oluşturuluyor.

public sealed class Singleton
    {
        Singleton()
        {
            Console.WriteLine("Singleton contructor çalıştı.");
        }

        public static Singleton Instance
        {
            get
            {
                return Nested.instance;
            }
        }

        public static void MyMethod1()
        {
            Console.WriteLine("MyMethod1 çalıştı..");
        }

        public void MyMethod2()
        {
            Console.WriteLine("MyMethod2 çalıştı..");
        }

        class Nested
        {
            static Nested()
            {
                instance = new Singleton();
                Console.WriteLine("Nested constructor çalıştı");
            }

            internal static readonly Singleton instance;
        }
    }

Print | posted on Sunday, May 11, 2008 10:27 PM | Filed Under [ Design Patterns C# ]

Feedback

No comments posted yet.

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 5 and 3 and type the answer here:

Powered by: