单例模式的简单应用

单例模式主要是为了确保只有单个对象被创建,主要解决一个类的对象频繁地创建与销毁

我们通过如下示例来了解单例模式的作用,以及实现方案

如上图,我们只要点击一次"普通模式"的菜单,即会创建一个新的窗体对象。

而我们如果**使用单例模式,**即点击"单例模式"菜单,当唯一对象不存在的时候,会创建一个窗体,但是当窗体已经

存在的时候,将不会创建新的窗体。

  1. // 1、定义一个私有的静态的对象
  2. //2、定义一个公有的方法访问它,而不是再new 一个对象
cs 复制代码
// 1、定义一个私有的静态对象
private static FormSingle1 frm;

//2、定义一个公有的方法访问它
public static FormSingle1 CreateFrom()

{

    if (frm == null || frm.IsDisposed)

    {    //当实例不存在时 或实例被释放时

        frm = new FormSingle1();

    }

    return frm;

}

//******************************8
private void 普通模式ToolStripMenuItem_Click(object sender, EventArgs e)

 {

     FormCommon formCommon = new FormCommon();

     formCommon.MdiParent = this;

     formCommon.Show();

 }

//******************************
 private void 单例模式ToolStripMenuItem_Click(object sender, EventArgs e)

 {

     FormSingle1 frm = FormSingle1.CreateFrom();

     frm.MdiParent = this;

     frm.Show();

 }
相关推荐
rockey6271 小时前
基于AScript的SQL脚本语言发布啦!
sql·c#·.net·script·expression·动态脚本
z落落3 小时前
C# 四种特殊类:抽象类、密封类、静态类、部分类
开发语言·c#
caimouse3 小时前
Reactos 第 4 章 对象管理 — 4.5 几个常用的内核函数
c语言·windows·架构
caimouse4 小时前
Reactos 第 4 章 对象管理 — 4.3 句柄和句柄表(Handle & Handle Table)
c语言·windows·架构
王cb4 小时前
WinRT Server and Client c#
开发语言·c#
咸鱼翻身小阿橙4 小时前
在VScode使用C#并且调用opencv库
vscode·opencv·c#
Chase_______5 小时前
【Java基础 | 15】集合框架(中):Set、HashSet、TreeSet 与哈希表
java·windows·散列表
caimouse5 小时前
Windows NT 内核架构(主通用模型)流 NT 5.x/10+
windows·架构
caimouse5 小时前
Reactos 第 3 章 内存管理 — 【中篇】Hyperspace、系统空间、API 与异常
c语言·开发语言·windows·架构
caimouse6 小时前
Reactos 第 4 章 对象管理 — 4.1 对象与对象目录
服务器·c语言·开发语言·windows·架构