JAVA设计模式-单例模式
单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例
Java中单例模式定义:“一个类有且仅有一个实例,并且自行实例化向整个系统提供。”
常用的有两种实现方式懒汉式和饿汉式
1、懒汉式
顾名思义,懒汉式是在使用的时候才会进行加载的方式,所以在初次加载会耗费一点性能
示例代码
public class SingleTest {
private SingleTest(){};
public static SingleTest instance = null ;//懒汉
public static SingleTest getInstance(){
if(instance==null){
instance = new SingleTest();
}
return instance;
}
}
2、饿汉式
类初始化的时候就创建一个对象,在使用的时候直接使用,即便不用也会占用一定的内存。
示例代码:
public class SingleTest {
private SingleTest(){};
public static SingleTest instance = new SingleTest() ;//饿汉
public static SingleTest getInstance(){
return instance;
}
}
3、区别
(1)性能方面
懒汉在第一次创建时耗费性能,饿汉在不用的时候占用部分性能 各有利弊
(2)线程安全方面
饿汉式是线程安全的 ,懒汉线程不安全
4、解决懒汉式线程不安全问题
(1)synchronized 同步 此方法每次调用时都会进行同步,但是实际中绝大多数情况下是不需要同步的,浪费性能
public class SingleTest {
private SingleTest(){};
public static SingleTest instance = null ;//懒汉
public static synchronized SingleTest getInstance(){
if(instance==null){
instance = new SingleTest();
}
return instance;
}
}
(2)双重检查同步 此方法避免了绝大多数不需要同步的情况
public class SingleTest {
private SingleTest(){};
public static SingleTest instance = null ;//懒汉
public static SingleTest getInstance(){
if(instance==null){
synchronized (SingleTest.class) {
if(instance==null){
instance = new SingleTest();
}
}
}
return instance;
}
}
(3)静态内部类方式
public class SingleTest {
private SingleTest(){};
public static SingleTest instance = null ;//懒汉
private static class LoadInstance {
private static final SingleTest INSTANCE = new SingleTest();
}
public static SingleTest getInstance(){
return LoadInstance.INSTANCE;
}
}
博客新人,欢迎各位大神反馈意见和建议,共同进步。。。