一.概念理解:
1.什么是单例模式?
就是整个类就有一个实例,并提供一个访问它的全局访问点。
2.单例模式的存在形式?
饥汉模式、饱汉模式,双重锁模式
图
3.类结构图
图
二.代码示演
1.饥汉模式
public class SingletonHungry {
private static SingletonHungry singleton = new SingletonHungry();
private SingletonHungry() {
}
public static SingletonHungry getInstance() {
return singleton;
}
}
2.饱汉模式
public class SingletonFull {
private static SingletonFull singleton;
private SingletonFull() {
}
public static synchronized SingletonFull getInstance() {
if (singleton == null)
singleton = new SingletonFull();
return singleton;
}
}
3.双重锁模式
public class SingletonTwoBlotLock {
private static SingletonTwoBlotLock singleton;
private SingletonTwoBlotLock() {
}
public static SingletonTwoBlotLock getInstance() {
if (singleton == null) {
synchronized (SingletonTwoBlotLock.class) {
if (singleton == null) {
singleton = new SingletonTwoBlotLock();
}
}
}
return singleton;
}
}
运行结果:
图