单例就是该类是能返回一个实例。
单例所具备的特点:
1、私有化的构造函数
2、私有的静态的全局变量
3、共有的静态方法
单例分为懒汉式、饿汉式和双层锁式
//饿汉模式
public class Singleton1{
private static Singleton1 instance = new Singleton1();
private Singleton1(){
}
private static Singleton1 single = new Singleton1();
public static Singleton1 getInstance(){
}
}
//懒汉式
public class Singleton2{
private Singleton2(){}
private static Singleton2 single = null;
public static Singleton2 getInstance(){
if(single == null){
single = new Singleton2();
}
return single;
}
}
//双层锁式
public class Singleton3{
private Singleton3(){}
private static Singleton3 single;
public static Singleton3 getInstance(){
if(null == single){
synchronized(Singleton3.class){
if(null == single){
single = new Singleton3();
}
}
}
return single;
}
}
单例的特点及模式
最新推荐文章于 2024-09-16 10:31:05 发布