什么是单例模式?
作为对象的创建模式,单例模式确保某一个类只有一个实例,而且自行实例化(即私有构造)并向整个系统提供这
个实例,此为单例模式。而这个类就称为单例类。
单例模式的特点:
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);
}
}
樱花校园模拟器4399中文版
樱花校园模拟器4399中文版,十分奇趣好玩的3d校园冒险模拟
我的暑假秘密回忆繁星新春版
我的暑假秘密回忆繁星新春版是一款少女模拟养成类休闲游戏。这款
樱花校园模拟器国际版
樱花校园模拟器国际版,一个超级自由超级好玩的自由恋爱模拟的游
饥荒海难九游版
饥荒海难九游版,带你去真实的海岛上感受一下什么才是真正的孤岛
盖瑞模组体验版最新版
盖瑞模组体验版是玩法非常丰富多元化的沙盒建造游戏,玩家可以在