二十三.单例模式
单例模式:
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
类自身负责保存它的唯一实例。
注意:多线程
使用锁,或C#静态类——Demo3
Demo1:——WinForm
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.IsMdiContainer = true;
}
private void button1_Click(object sender, EventArgs e)
{
Form2.Show1().Show();
}
}
public partial class Form2 : Form
{
private static Form
private Form2()
{
InitializeComponent();
}
publicstatic Form2 Show1()
{
if (f == null || f.IsDisposed)
{
f = new Form2();
f.MdiParent = Form1.ActiveForm;
}
return f;
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
Demo2:
classProgram
{
static void
{
child c1= child.GetChild();
child c2 = child.GetChild();
c1.A = 5;
Console.WriteLine(c2.A);
Console.ReadKey();
}
}
class child
{
private static child c;
private child() { }
public staticchild GetChild()
{
if (c == null)
{
c = new child();
}
return c;
}
private int a;
public int A
{
get { return a; }
set { a = value; }
}
}
Demo3:
1:
privatestatic child c;
private static readonly object syncRoot = newobject();//锁
private child() { }
public static child GetChild()
{
lock (syncRoot)
{
if (c == null)
{
c = new child();
}
}
return c;
}
2:双重锁
privatestatic child c;
private static readonly object syncRoot = new object();//锁
private child() { }
public static child GetChild()
{
if (c == null)
{
lock (syncRoot)
{
if (c == null)
{
c = new child();
}
}
}
return c;
}
3:静态类
sealed class child//sealed声明静态类,阻止派生增加实例
{
privatestatic readonly child c=new child();//第一次引用类的任何成员时创建实例。公共语言运行库负责处理变量初始化
private child() { }
public static child GetChild()
{
returnc;
}
private int a;
public int A
{
get { return a; }
set { a = value; }
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】博客园携手 AI 驱动开发工具商 Chat2DB 推出联合终身会员
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步