一.单例模式
1.懒汉模式
只有在第一次调用的时候会实例化对象
public class Singleton1{
private static Singleton1 instance = null;
//构造方法
private Singleton1(){
}
/**
*单线程模式
*/
public static Singleton1 getInstanceA(){
if(instace = null){
instance = new Singleton1();
}
retrun instance
}
/**
* 多线程环境 我们加个关键字,让方法变成同步方法就好了
*/
public static synchronized Singleton1 getInstanceB() {
if (instance == null) {
instance = new Singleton1();
}
return instance;
}
/**
* 双重检查加锁(
*/
public static Singleton1 getInstanceC() {
// 先判断实例是否存在,若不存在再对类对象进行加锁处理
if (instance == null) {
synchronized (Singleton1.class) {
if (instance == null) {
instance = new Singleton1();
}
}
}
return instance;
}
}
2.饿汉模式
饿汉式单例类:在类初始化时,已经自行实例化。
public class Singleton2{
private static Singleton2 instance = new Singleton2();
private Singleton2() {
}
public static Singleton2 getInstance(){
returin instance;
}
}