单例模式
定义
所谓单例,指的就是单实例,有且仅有一个类实例,这个单例不应该由人来控制,而应该由代码来限制,强制单例。
应用场景
1.整个程序的运行中只允许有一个类的实例;
2.需要频繁实例化然后销毁的对象。
3.创建对象时耗时过多或者耗资源过多,但又经常用到的对象。
4.方便资源相互通信的环境
代码实现
饿汉式
/**
* 饿汉式
* @author: _先森
*/
public class Singleton {
private Singleton() {
}
private static Singleton instance =new Singleton();
public static Singleton getInstance(){
return instance;
}
public void dosomething(){
System.out.println("调用成功");
}
}
懒汉式
/**
* 懒汉式
* @author: _先森
*/
public class Singleton2 {
private Singleton2() {
}
private static Singleton2 instance=null;
public static Singleton2 getInstance(){
if (instance==null){
instance=new Singleton2();
}
return instance;
}
}
懒汉式在多线程场景下可能出现的线程安全问题的解决方法:
/**
* 懒汉式
* @author: _先森
*/
public class Singleton2 {
private Singleton2() {
}
private static Singleton2 instance = null;
// 方式一 通过同步代码块方式实例化
public static Singleton2 getInstance() {
synchronized (Singleton2.class) {
if (instance == null) {
instance = new Singleton2();
}
}
return instance;
}
// 方式二 通过方法给实例化方法填加同步锁
// public synchronized static Singleton2 getInstance(){
// if (instance==null){
// instance=new Singleton2();
// }
// return instance;
// }
// 方式三 双重校验锁
// public static Singleton2 getInstance(){
// if (instance==null){
// synchronized (Singleton2.class){
// if (instance==null){
// instance=new Singleton2();
// }
// }
// }
// return instance;
// }
}