분류 전체보기 (328)
.NET (111)
S/W tip (35)
etc (63)
DB (34)
HOT item~! (48)
Disign pettens (4)
UX (6)
나의 S/W (2)
개발관련 이슈 (16)
Diary (1)
웹플러스 (1)
calendar
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
tags
archive
link
ColorSwitch 00 01 02
▣  C# Singleton Pattern 구현 - Disign pettens - 2009. 5. 14. 14:36

http://blog.naver.com/dolmoon?Redirect=Log&logNo=60051507361
 

참조 : http://www.yoda.arachsys.com/csharp/singleton.html


다음은 Windows Form을 싱글턴으로 구현한 예제


using System.Windows.Forms;

namespace SingletonSample
{
    public partial class SingletonForm : Form
    {

        //클래스 자신을 인스턴스로 저장할 멤버

        // --> 엄밀히 말하면 클래스의 유일한 인스턴스를 저장할 멤버
        private volatile static SingletonForm _singletonForm;
        //Dummy object for thread-safety
        private static object dummy = new object();

        //생성자를 감춰서 외부에서는 클래스 인스턴스를 생성할 수 없게 만듦.

        private SingletonForm()
        {
            InitializeComponent();
        }

      

        //Property형식으로 Singleton 패턴을 구현

        public static SingletonForm Instance
        {
            get
            {
                //lock은 블럭 안의 코드가 실행되는 동안 다른 쓰레드가
                //이 블럭이 실행하지 못하도록 막음(다른 쓰레드는 이 블럭이
                //완료될 때까지 기다림).
                lock(dummy)
                {

                    //_singletonForm이 static으로 선언되어 있으므로 이 클래스의 인스턴스는

                    //항상 하나만 존재하게 됨.

                    if (_singletonForm == null || _singletonForm.IsDisposed)
                        //클래스 인스턴스 생성
                        _singletonForm = new SingletonForm();
                    return _singletonForm;
                }
            }
        }

        //Method를 이용하여 Singleton 패턴을 구현
        //public static SingletonForm GetInstance()
        //{
        //    lock (dummy)
        //    {
        //        if (_singletonForm == null || _singletonForm.IsDisposed)
        //        {
        //            _singletonForm = new SingletonForm();
        //        }
        //    }
        //    return _singletonForm;
        //}
    }

  

    static class Program
    {
        [STAThread]
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);


            SingletonForm form1 = SingletonForm.Instance;
            form1.Text = "First SingleForm?";
            form1.Show();
            form1.Visible = false;
            Forms.SingletonForm form2 = Forms.SingletonForm.Instance; //form1을 다시 얻어 온다.
            form2.Text += " or Second SingleForm?";
            form2.ShowDialog();
        }
    }  
}


실행해보면 form2.Text가 "First SingleForm? or Second SingleForm?"이 된다. 즉, form1과 form2는 같은 form이다.


articles
recent replies
recent trackbacks
notice
Admin : New post