步骤:
1、将要创建的单例对象构造函数私有化
2、提供一个静态方法,返回一个对象
3、创建一个单例
例如在form1中打开form2窗体,(form1按钮单击创建窗体)
form1 代码如下:
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = Form2.GetSingle();
form2.Show();
}
form2 代码如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
/*
步骤:1、将要创建的单例对象构造函数私有化
2、提供一个静态方法,返回一个对象
3、创建一个单例
*/
public partial class Form2 : Form
{
public static Form2 FormSingle = null;
private Form2() //将需要单例的私有化
{
InitializeComponent();
}
public static Form2 GetSingle()
{
if (FormSingle==null)
{
FormSingle = new Form2();
}
return FormSingle;
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
FormSingle = null; //标志单例被关闭,允许下次创建
}
}
}