C# 单例设计模式

来源:互联网 发布:加速器有mac 编辑:程序博客网 时间:2024/05/29 11:06

单例类:

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 Form4 FrmFour   //单例对象中的属性        {            get;            set;        }        public Form5 FrmFive        {            get;            set;        }        public void CreateForm()        {                     }    }}
单例类的使用:
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 Form1_Load(object sender, EventArgs e)        {        }        private void button2_Click(object sender, EventArgs e)        {            if (SingleObject.GetSingle().FrmThree == null)   //先通过静态方法获取单例对象(GetSingle()),然后获取单例对象的单例属性。            {                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();        }    }}





原创粉丝点击