有些窗体我们不希望生成多个实例,例如Windows系统中的控制面板等,这些窗体只有一个实例,可以采用我们现在要说的单件来实现。
现在用一个单位的窗体调用来说明单件,从Form1中调用Form2,代码如下:
- Form1窗体
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- namespace singleton
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- Form frm = Form2.Singleton();
- frm.Show();
- }
- }
- }
- Form2窗体
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- namespace singleton
- {
- public partial class Form2 : Form
- {
- private static Form2 frm = null;
- private Form2()
- {
- InitializeComponent();
- }
- public static Form2 Singleton()
- {
- if (frm == null)
- {
- frm = new Form2();
- }
- return frm;
- }
- private void Form2_FormClosing(object sender, FormClosingEventArgs e)
- {
- try
- {
- this.Dispose(true);
- frm = null;
- }
- catch
- { }
- }
- }
- }