单例模式简介
- 模式属于创立型模式,它提供了一种创建对象的最佳形式。
- 这种模式波及到一个繁多的类,该类负责创立本人的对象,同时确保只有单个对象被创立。
- 这个类提供了一种拜访其惟一的对象的形式,能够间接拜访,不须要实例化该类的对象。
- 次要分为:饿汉模式和懒汉模式
饿汉模式
//饿汉模式
public class Hungry {
private static Hungry hungry = new Hungry();
private Hungry() {
}
public static Hungry getInstance() {
return hungry;
}
}
懒汉模式(单线程)
public class LazyMan01 {
private static LazyMan01 lazyMan;
private LazyMan01() {
}
public static LazyMan01 getInstance() {
if (lazyMan == null) {
lazyMan = new LazyMan01();
}
return lazyMan;
}
}
懒汉模式(多线程)
public class LazyMan02 {
private volatile static LazyMan02 lazyMan;
private LazyMan02() {
}
//双重检测锁 懒汉单例模式 DCL懒汉模式
public static LazyMan02 getInstance() {
if (lazyMan == null) {
synchronized (LazyMan02.class) {
if (lazyMan == null) {
lazyMan = new LazyMan02();
}
}
}
return lazyMan;
}
}
发表回复