在程序设计的时候,有时会遇到一些要求只能创建一个实例的时候(如开发窗口时只允许打开一个窗
口,即只能创建一个窗口句柄)。
在设计的时候要注意将该实例的构造函数私有化(即用private修饰),从而达到不让使用者再创建该类
实例
/*
单例设计模式,使用静态成员函数返回该类实例的地址
推荐使用饿汉式
*/
//饿汉式,直接申请一个singleInstance空间
class singleInstance
{
private singleInstance(){} //不允许使用者独立创建该类实例
static singleInstance s = new singleInstance();
static singleInstance getInstance()
{ return s; }
//中间添加自己所需要的代码
}
//懒汉式,待需要用到时才申请一个空间(特点延迟加载)
class singleInstance
{
private singleInstance(){} //不允许使用者独立创建该类实例
static singleInstance s;
static singleInstance getInstance()
{
if (s==null)//双重判断,减少判断锁的次数
{
synchronized(singleInstance.class) //加锁,只允许进来一次
{
if (s==null)
{
s = new singleInstance(); //延迟加载
}
}
}
return s;
}
//中间添加自己所需要的代码
}
口,即只能创建一个窗口句柄)。
在设计的时候要注意将该实例的构造函数私有化(即用private修饰),从而达到不让使用者再创建该类
实例
/*
单例设计模式,使用静态成员函数返回该类实例的地址
推荐使用饿汉式
*/
//饿汉式,直接申请一个singleInstance空间
class singleInstance
{
private singleInstance(){} //不允许使用者独立创建该类实例
static singleInstance s = new singleInstance();
static singleInstance getInstance()
{ return s; }
//中间添加自己所需要的代码
}
//懒汉式,待需要用到时才申请一个空间(特点延迟加载)
class singleInstance
{
private singleInstance(){} //不允许使用者独立创建该类实例
static singleInstance s;
static singleInstance getInstance()
{
if (s==null)//双重判断,减少判断锁的次数
{
synchronized(singleInstance.class) //加锁,只允许进来一次
{
if (s==null)
{
s = new singleInstance(); //延迟加载
}
}
}
return s;
}
//中间添加自己所需要的代码
}