單例模式演示-2-39-07

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 
10 namespace _02利用單例模式的思想實現窗體只顯示一個
11 {
12     public partial class Form2 : Form
13     {
14         private Form2()
15         {
16             InitializeComponent();
17         }
18 
19         private static Form2 _form2Instance;
20         private static readonly object syn = new object();
21         public static Form2 GetInstance()
22         {
23             if (_form2Instance == null || _form2Instance.IsDisposed)
24             {
25                 lock (syn)
26                 {
27                     if (_form2Instance == null || _form2Instance.IsDisposed)
28                     {
29                         _form2Instance = new Form2();
30                     }
31                 }
32                 
33             }
34             return _form2Instance;
35         }
36     }
37 }
 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 
10 namespace _02利用單例模式的思想實現窗體只顯示一個
11 {
12     public partial class Form1 : Form
13     {
14         public Form1()
15         {
16             InitializeComponent();
17         }
18         //Form2 f2 = null;
19         private void button1_Click(object sender, EventArgs e)
20         {
21             //if (f2 == null || f2.IsDisposed)
22             //{
23             //    f2 = new Form2(); f2.Show();
24             //}
25             //else
26             //{
27             //    f2.Activate();
28             //}
29             Form2 f2 = Form2.GetInstance();
30             f2.Show();
31 
32 
33         }
34     }
35 }
相關文章
相關標籤/搜索