单例模式作为模式中的第一步,所用之广泛,在此不详细介绍,主要介绍如何运用于用于C#
在整个程序中,我们要保证对象必须是唯一的。
实现:
—->第一步:构造函数私有化
—->第二步:声明一个静态字段,作为全局唯一的单例对象
—->第三步:声明一个静态函数,返回全局唯一的对象
现在要求这些窗体在内存中只有一个对象,如果给每一个窗体设计一个单例模式,这样是不现实的。
干脆创建一个单例类,这个类的对象只可能是一个,类的成员只能是唯一!
创建一个对象,在堆里面分配一定的空间,里面的成员变量也要占用空间。
把窗体作为对象存储到单例类中!
【单例类】:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _04单例设计模式
{
class SingleObject
{
private SingleObject()
{ }
private static SingleObject _single = null;
public static SingleObject GetSingle()
{
if (_single == null)
{
_single = new SingleObject();
}
return _single;
}
public Form3 FrmThree
{
get;
set;
}
public void CreateForm()
{
}
}
}
【窗体1】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace _04单例设计模式
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = Form2.GetSingle();//new Form2();
frm2.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (SingleObject.GetSingle().FrmThree == null)
{
SingleObject.GetSingle().FrmThree = new Form3();
}
SingleObject.GetSingle().FrmThree.Show();
}
private void button3_Click(object sender, EventArgs e)
{
if (SingleObject.GetSingle().FrmFour == null)
{
SingleObject.GetSingle().FrmFour = new Form4();
}
SingleObject.GetSingle().FrmFour.Show();
}
}
}
【窗体2】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace _04单例设计模式
{
public partial class Form2 : Form
{
//第一步:构造函数私有化
private Form2()
{
InitializeComponent();
}
//第二部:声明一个静态的字段用来存储全局唯一的窗体对象
private static Form2 _single = null;
//第三步:通过一个静态函数返回一个全局唯一的对象
public static Form2 GetSingle()
{
if (_single == null)
{
_single = new Form2();
}
return _single;
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
//当你关闭窗体的时候 让窗体2的资源不被释放
_single = new Form2();
}
}
}
【窗体3】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace _04单例设计模式
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
}
}