目录
0、定义
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
1、单件模式的一个角色
- 单件类(Singleton):单件类只可以创建出一个实例。
2、单件模式的UML类图

3、示例代码
简单的单件模式
java
package xyz.jangle.design.singleton;
/**
* 单件模式
* @author Administrator
*
*/
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {
System.out.println("简单的单例模式");
};
public static synchronized Singleton getInstance() {
if(uniqueInstance==null) {
uniqueInstance= new Singleton();
}
return uniqueInstance;
}
}
使用双重检测的单件模式
java
package xyz.jangle.design.singleton;
/**
* 单例模式,双重检测。
* @author Administrator
*
*/
public class SingletonDouble {
private static SingletonDouble uniqueInstance;
private SingletonDouble() {
System.out.println("单例模式,使用双重检测");
}
public static SingletonDouble getInstance() {
if(uniqueInstance==null) {
synchronized (SingletonDouble.class) {
if(uniqueInstance==null) {
uniqueInstance = new SingletonDouble();
}
}
}
return uniqueInstance;
}
}
使用静态内部类的单件模式
java
package xyz.jangle.design.singleton;
/**
* 使用静态内部类实现单例模式
* @author Administrator
*
*/
public class SingletonInnerStatic {
private SingletonInnerStatic() {
System.out.println("静态内部类的单例模式");
};
private static class SingletonInner {
private static final SingletonInnerStatic INSTANCE = new SingletonInnerStatic();
}
public static SingletonInnerStatic getInstance() {
return SingletonInner.INSTANCE;
}
}
客户端(使用)
java
package xyz.jangle.design.singleton;
public class AppMain17 {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(()->{
System.out.println("获取单例模式");
Singleton instance = Singleton.getInstance();
System.out.println("成功获取单例"+instance);
}).start();
}
for (int i = 0; i < 10; i++) {
new Thread(()->{
System.out.println("获取单例模式");
SingletonDouble instance = SingletonDouble.getInstance();
System.out.println("成功获取单例"+instance);
}).start();
}
for (int i = 0; i < 10; i++) {
new Thread(()->{
System.out.println("获取单例模式");
SingletonInnerStatic instance = SingletonInnerStatic.getInstance();
System.out.println("成功获取单例"+instance);
}).start();
}
}
}