什么是单例模式?
作为对象的创建模式,单例模式确保某一个类只有一个实例,而且自行实例化(即私有构造)并向整个系统提供这
个实例,此为单例模式。而这个类就称为单例类。
单例模式的特点:
1.单例模式只能有一个实例;
2.单例模式必须有一个私有构造函数;
3.单例模式必须提供一个全局访问点,供整个系统使用。
注意:
1.单例模式中的构造函数可以为protected类型以允许子类派生,但绝对不可以是public;
2.单例模式一般不要求支持icloneable接口,单例模式一般不要支持序列化,因为这都会导致对象实例,与单例
模式的初衷相违背;
3.单例模式只考虑到了对象创建的管理,没有考虑对象销毁的管理。对于支持垃圾回收的平台来讲,我们一般没
有必要对其销毁进行特殊的管理。
4.不能应对多线程环境:在多线程环境下,使用单例模式仍然有可能得到单例类的多个实例对象。
单例模式的典型案例(c#)
winform中的父窗体(mdiparent)与子窗体的关系就应该是一个典型的单例模式。
首先,在visual studio中创建一个windows应用程序,创建两个窗体from1和form2,将form1设为父窗体,form2
using system.threading;
using system.windows.forms;
static class program
{
public static eventwaithandle programstarted;
[stathread]
static void main()
{
// 尝试创建一个命名事件
bool createnew;
programstarted = new eventwaithandle(false, eventresetmode.autoreset, "mystartevent", out createnew);
// 如果该命名事件已经存在(存在有前一个运行实例),则发事件通知并退出
if (!createnew)
{
programstarted.set();
return;
}
application.enablevisualstyles();
application.setcompatibletextrenderingdefault(false);
application.run(new form1());
}
}
c# code
// form1.cs
//
using system;
using system.windows.forms;
using system.threading;
public partial class form1 : form
{
notifyicon notifyicon1 = new notifyicon();
public form1()
{
//initializecomponent();
this.notifyicon1.text = "double click me to show window";
this.notifyicon1.icon = system.drawing.systemicons.information;
this.notifyicon1.doubleclick += onnotifyicondoubleclicked;
this.sizechanged += onsizechanged;
threadpool.registerwaitforsingleobject(program.programstarted, onprogramstarted, null, -1, false);
}
// 当最小化时,放到系统托盘。
void onsizechanged(object sender, eventargs e)
{
if (this.windowstate == formwindowstate.minimized)
{
this.notifyicon1.visible = true;
this.visible = false;
}
}
// 当双击托盘图标时,恢复窗口显示
void onnotifyicondoubleclicked(object sender, eventargs e)
{
this.visible = true;
this.notifyicon1.visible = false;
this.windowstate = formwindowstate.normal;
}
// 当收到第二个进程的通知时,显示气球消息
void onprogramstarted(object state, bool timeout)
{
this.notifyicon1.showballoontip(2000, "hello", "i am here...", tooltipicon.info);
}
}
茶杯头甜蜜终章dlc 官方手机版v1.0.0.3
下载火柴人传说暗影格斗内置菜单 最新版v3.0.1
下载荒野乱斗测试服 安卓版v61.10.3
下载荒野乱斗彩虹服 安卓版v61.10.3
下载寒霜启示录 安卓版v1.25.10
寒霜启示录是一款生存模拟游戏,不少玩家可能对于末日都有着自己
末日城堡免广告版 安卓最新版v0.7.1
末日城堡免广告版是一款非常好玩的模拟经营类游戏,内部可以不看
甜蜜人生模拟器 最新版v1.4.5
甜蜜人生模拟器是一款非常好玩的模拟恋爱手游,玩家在这里能够对
武器锻造师内置功能菜单 v10.4
武器锻造师内置菜单版是游戏的破解版本,在该版本中为玩家提供了
开放空间overfield 安卓版v1.0.5
开放空间Overfield是一款箱庭养成经营手游,让你在广阔