简单工厂设计模式
简单工厂设计模式说的通俗点就是保证对象在项目中出现的唯一性,并不是把原先对象先清除,而是如果没有该对象就实例化,再出现,否则,就出现原先的对象
用WinForm窗体为例
1、建立“简单工厂”的模型(自己建立一个对象,确保该对象最多出现一次,最少出现一次,即唯一性)
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 _04单例设计模式 11 { 12 public partial class Form2 : Form 13 { 14 //第一步:构造函数私有化 15 private Form2() 16 { 17 InitializeComponent(); 18 } 19 20 //第二部:声明一个静态的字段用来存储全局唯一的窗体对象 21 private static Form2 _single = null; 22 //第三步:通过一个静态函数返回一个全局唯一的对象 23 24 public static Form2 GetSingle() 25 { 26 if (_single == null) 27 { 28 _single = new Form2(); 29 } 30 return _single; 31 } 32 33 private void Form2_FormClosing(object sender, FormClosingEventArgs e) 34 { 35 //当你关闭窗体的时候 让窗体2的资源不被释放 36 _single = new Form2(); 37 } 38 } 39 }
2、在窗体中设计功能。form1的功能如图
代码:
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.Threading.Tasks; 9 using System.Windows.Forms; 10 11 namespace WindowsFormsApplication3 12 { 13 public partial class Form1 : Form 14 { 15 public Form1() 16 { 17 InitializeComponent(); 18 } 19 20 private void button1_Click(object sender, EventArgs e) 21 { 22 //没有form2,就先实例化,否则出现原先的form2 23 if (SingleObject.GetSingle().F2 == null) 24 { 25 SingleObject.GetSingle().F2 = new Form2(); 26 } 27 SingleObject.GetSingle().F2.Show(); 28 29 } 30 31 private void button2_Click(object sender, EventArgs e) 32 { 33 if (SingleObject.GetSingle().F3 == null) 34 { 35 SingleObject.GetSingle().F3 = new Form3(); 36 } 37 SingleObject.GetSingle().F3.Show(); 38 } 39 } 40 }
完!
增:全面代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsFormsApp9.App_Code { class SingleObject { private static SingleObject _single; private static readonly object locker = new object(); private SingleObject() { } public static SingleObject Getsingle() { if (_single == null) { lock (locker) { if (_single == null) { _single = new SingleObject(); } } } return _single; } } }