AS WE KNOW ,单例模式是最基础的设计模式,在设计模式方面,单例模式有很多作用,另外在框架里面,ioc里面的bean默认就是单例。实际编程应用场景中,有一些对象其实我们只需要一个,比如线程池对象、缓存、系统全局配置对象等。这样可以就保证一个在全局使用的类不被频繁地创建与销毁,节省系统资源。
懒汉式
package pri.niddles.model;
//单线程还行 多线程不行
public class Lazy {
private Lazy(){
}
private static Lazy l ;
public static Lazy getInstance(){
if (l==null){
l = new Lazy();
}else {
System.out.println("不能重复new 对象");
}
return l;
}
}
package pri.niddles.model;
//版本2 加个锁
public class Lazy2 {
private Lazy2(){
}
private static Lazy2 l ;
public static Lazy2 getInstance(){
if (l==null){
synchronized (Lazy2.class){
if (l==null){
l = new Lazy2();
}else {
System.out.println("不能重复new 对象");
}
}
}
return l;
}
}
饿汉式
package pri.niddles.model;
//花样取对象 哈哈哈
//单例分为饿汉 懒汉 直接给和判断的区别
public class Hungry {
//构造方法 也就是new这个对象的骨架
//私有的最后不能更改的静态的(变成类的东西)
private final static Hungry h = new Hungry();
private Hungry() {
}
public static Hungry getInstance(){
return h;
}
public static void main(String[] args) {
}
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}
public class Singleton {
private static Singleton instance;
static {
instance = new Singleton();
}
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
双重检测锁模式
public class Singleton {
private volatile static Singleton singleton;
private Singleton() {}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
静态内部类
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}