指一个类只有一个实例,且该类能自行创建这个实例的一种模式。
例如,Windows 中只能打开一个任务管理器,这样可以避免因打开多个任务管理器窗口而造成内存资源的浪费,或出现各个窗口显示内容的不一致等错误。
在计算机系统中,还有 Windows 的回收站、操作系统中的文件系统、多线程中的线程池、显卡的驱动程序对象、打印机的后台处理服务、应用程序的日志对象、数据库的连接池、网站的计数器、Web 应用的配置对象、应用程序中的对话框、系统中的缓存等常常被设计成单例。
单例模式的主要角色如下。
单例模式有两种实现方式,分别为懒汉式单例与饿汉式单例两种。
懒汉式单例的特点是在类加载时没有生成单例,只有当第一次被调用getInstance()方法时才会去第一次创建这个单例对象。
public class LazySingleton
{
private static volatile LazySingleton instance = null; //保证 instance 在所有线程中同步
private LazySingleton(){} //private 避免类在外部被实例化
public static synchronized LazySingleton getInstance()
{
//getInstance 方法前加同步
if(instance == null)
{
instance = new LazySingleton();
}
return instance;
}
}
注意:如果编写的是多线程程序,则不要删除上例代码中的关键字 volatile 和 synchronized,否则将存在线程非安全的问题。如果不删除这两个关键字就能保证线程安全,但是每次访问时都要同步,会影响性能,且消耗更多的资源,这是懒汉式单例的缺点。
该模式的特点是类一旦加载就创建一个单例,保证在调用 getInstance 方法之前单例已经存在了。
public class HungrySingleton
{
private static final HungrySingleton instance=new HungrySingleton();
private HungrySingleton(){}
public static HungrySingleton getInstance()
{
return instance;
}
}
饿汉式单例在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变,所以是线程安全的,可以直接用于多线程而不会出现问题。
【例】分别用懒汉式单例模式和饿汉式单例模式模拟产生美国当今总统对象。
分析:在每一届任期内,美国的总统只有一人,所以本实例适合用单例模式实现,以下是实现代码。
1.懒汉式
public class SingletonLazy {
public static void main(String[] args) {
PresidentLazy president1 = PresidentLazy.getInstance();
PresidentLazy president2 = PresidentLazy.getInstance();
if (president1 == president2) {
System.out.println("他们是同一个人!");
} else {
System.out.println("他们不是同一个人!");
}
}
}
class PresidentLazy {
private static volatile PresidentLazy instance = null;//保证instance在所有线程中同步
//私有化构造方法避免在外部类被实例
private PresidentLazy() {
System.out.println("产生一个总统!");
}
public static synchronized PresidentLazy getInstance() {
if (instance == null) {
instance = new PresidentLazy();
} else {
System.out.println("已经有一个总统");
}
return instance;
}
}
运行结果:
产生一个总统!
已经有一个总统
他们是同一个人!
2.饿汉式
public class SingletonEager {
public static void main(String[] args) {
PresidentEager president1 = PresidentEager.getInstance();
PresidentEager president2 = PresidentEager.getInstance();
if (president1 == president2) {
System.out.println("他们是同一个人!");
} else {
System.out.println("他们不是同一个人!");
}
}
}
class PresidentEager {
private static final PresidentEager president = new PresidentEager();
private PresidentEager() {}
public static PresidentEager getInstance() {
return president;
}
}
运行结果:
他们是同一个人!
参考文章:http://c.biancheng.net/view/1338.html
原文:https://www.cnblogs.com/ThinMoon/p/13096499.html