什么是单列模式?
单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例。即一个类只有一个对象实例
通俗的讲就是每次只允许打开一个应用程序。
下面通过一个简单的案例演示一下:
一:在Form1中添加一个按钮不管点击多少次都只能打开一个窗体(Form2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
//窗体一: namespace WindowsFormsApplication3 { 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 groupControl1_Paint(object sender, PaintEventArgs e) { } } } |
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 |
//窗体2 namespace WindowsFormsApplication3 { public partial class Form2 : Form { //静态函数只能用静态成员 public static Form2 FrmSingle=null;//静态字段 private Form2()//将构造函数私有化 { InitializeComponent(); } public static Form2 GetSingle() { //Form2 frm2 = new Form2(); // return frm2; if (FrmSingle == null)//判断是否为空 { FrmSingle = new Form2(); } return FrmSingle; } } } |