设计模式-单件模式

来源:互联网 发布:linux 进程调度命令 编辑:程序博客网 时间:2024/05/21 06:52



经典的单件:

public class Singleton

{

private static Singleton uniqueInstance;

private Singleton() {}

public static Singleton getInstance()

{

if(uniqueInstance == null)

uniqueInstance  = new Singleton();

return uniqueInstance ;

}

//这里是其他的有用方法

}

处理多线程:

1.变成同步(synchronized)方法,但耗性能

public class Singleton

{

private static Singleton uniqueInstance;

private Singleton() {}

public static synchronized Singleton getInstance()

{

if(uniqueInstance == null)

uniqueInstance  = new Singleton();

return uniqueInstance ;

}

//这里是其他的有用方法

}

2.使用“急切”创建实例,而不是延迟实例化的做法

public class Singleton

{

private static Singleton uniqueInstance = new Singleton();

private Singleton() {}

public static Singleton getInstance()

{

return uniqueInstance ;

}

//这里是其他的有用方法

}

3.用“双重检查加锁”,在getInstance()中减少使用同步,只有第一次会进行同步

public class Singleton

{

private volatile static Singleton uniqueInstance;

private Singleton() {}

public static Singleton getInstance()

{

if(uniqueInstance == null)

{

synchronized(Singleton.class)

{

if(uniqueInstance  == null)

{

uniqueInstance  = new Singleton();

}

}

}

return uniqueInstance ;

}

//这里是其他的有用方法

}

volatile 关键词确保,当uniqueInstance 变量被初始化成Singleton实例时,多个线程正确地处理uniqueInstance 变量


程序退出时,确保单例为null:

// Ensure that the instance is destroyed when the game is stopped in the editor.
    void OnApplicationQuit()
    {
        s_Instance = null;
    }


0 0
原创粉丝点击