简介
单例类模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个例。在计算机系统中,线程池、缓存、日志对象、对话框、打印机、显卡的驱动程序对象常常被设计成单例。选择单例模式是为了避免不一致状态。
有如下特点:
1. 单例模式只能有一个实类。
2. 单例类必须自己创建自己的唯一实例。
3. 单例类必须给其他对象提供这一实例。
懒汉式单例
package com.cjm.mvnbook.test7;
/**
* 懒汉式单类模式
* @author chenjieming
*
*/
public class LazySingletonTest {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static LazySingletonTest singleton = null;
//构造方法私有化,不能通过构造方法创建实例化对象
private LazySingletonTest(){
}
public static LazySingletonTest getInstance(){
if(singleton == null){
singleton = new LazySingletonTest();
}
return singleton;
}
}
饿汉式单例
package com.cjm.mvnbook.test7;
public class HungerSingletonTest {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static HungerSingletonTest singletonTest = null;
private HungerSingletonTest(){
}
static {
singletonTest = new HungerSingletonTest();
}
public static HungerSingletonTest getInstance(){
return singletonTest;
}
}
运行测试:
package com.cjm.mvnbook.test7;
public class Test7 {
public static void main(String[] args) {
LazyTest();
unSafeHunger();
}
public static void LazyTest(){
LazySingletonTest singleton = LazySingletonTest.getInstance();
singleton.setName("张三");
LazySingletonTest singleton1 = LazySingletonTest.getInstance();
singleton1.setName("李四");
System.out.println(singleton.getName());
}
public static void unSafeHunger(){
HungerSingletonTest singletonTest = HungerSingletonTest.getInstance();
singletonTest.setName("张三");
HungerSingletonTest singletonTest1 = HungerSingletonTest.getInstance();
singletonTest1.setName("李四");
System.out.println(singletonTest.getName());
}
}
运行结果:李四 李四
总结
饿汉式和懒汉式区别:
- 从名称上可以看出来,饿汉就是类一旦加载,就把单例初始化完成,保证getInstance的时候,单例是已经存在的了,而懒汉比较懒,只有当调用getInstance的时候,才回去初始化这个单例;
- 饿汉式是天生线程安全的,而懒汉式有线程安全方面的问题;
实现懒汉式线程安全
1.在获取实例的方法上加同步
public static synchronized LazySingletonTest getInstance1(){
if(singleton == null){
singleton = new LazySingletonTest();
}
return singleton;
}
2.相对于第一种方法性能提升,不用每次同步
public static LazySingletonTest getInstance2(){
if(singleton == null){
synchronized (LazySingletonTest.class) {
if(singleton == null){
singleton = new LazySingletonTest();
}
}
}
return singleton;
}
3.静态内部类
private static class LazyHolder{
private static final LazySingletonTest INSTANCE = new LazySingletonTest();
}
public static final LazySingletonTest getInstance3(){
return LazyHolder.INSTANCE;
}