单例模式
单例模式定义:确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
1.饿汉式
public class Singleton1 {
private static Singleton1 instance = new Singleton1();
private Singleton1() {
}
public static Singleton1 getInstance() {
return instance;
}
}
2.懒汉式 (非线程安全)
public class Singleton2 {
private static Singleton2 instance = null;
private Singleton2() {
}
public static Singleton2 getInstance() {
if(null==instance){
instance=new Singleton2();
}
return instance;
}
}
3.懒汉式 (线程安全)
//1.方法加锁 2.方法内加锁 3.双重检验锁
public class Singleton3 {
private static Singleton3 instance = null;
private Singleton3() {
}
//1.
public static synchronized Singleton3 getInstance() {
if (null == instance) {
instance = new Singleton3();
}
return instance;
}
// 2.
// public static Singleton3 getInstance() {
// synchronized(Singleton3.class){
// if(null==instance){
// instance=new Singleton3();
// }
// }
// return instance;
// }
// 3.
// public static Singleton3 getInstance() {
// if (instance == null) {
// synchronized (Singleton3.class) {
// if (instance==null) {
// instance = new Singleton3();
// }
// }
//
// }
// return instance;
// }
}
4.静态内部类
public class Singleton4 {
private static class singletonHolder{
private static Singleton4 instance = new Singleton4();
}
private Singleton4() {
}
public static Singleton4 getInstance() {
return singletonHolder.instance;
}
}
5.枚举类
public enum Singleton5 {
instance;
public void doSomething() {
//do something...
}
}
补:多实例(设计模式之禅)
public class Emperor {
// 定义最多能产生的实例数量
private static int maxNumOfEmperor = 2;
// 每个皇帝都有名字,使用一个ArrayList来容纳,每个对象的私有属性
private static ArrayList<String> nameList = new ArrayList<String>();
// 定义一个列表,容纳所有的皇帝实例,考虑线程安全Vector替换ArrayList
private static ArrayList<Emperor> emperorList = new ArrayList<Emperor>();
// 当前皇帝序列号
private static int countNumOfEmperor = 0;
// 产生所有的对象
static {
for (int i = 0; i < maxNumOfEmperor; i++) {
emperorList.add(new Emperor("皇" + (i + 1) + "帝"));
}
}
// 传入皇帝名称,建立一个皇帝对象
private Emperor(String name) {
nameList.add(name);
}
// 随机获得一个皇帝对象
public static Emperor getInstance() {
Random random = new Random();
// 随机拉出一个皇帝,只要是个精神领袖就成
countNumOfEmperor = random.nextInt(maxNumOfEmperor);
return emperorList.get(countNumOfEmperor);
}
// 皇帝发话了
public static void say() {
System.out.println(nameList.get(countNumOfEmperor));
}
public static void main(String[] args) {
// 定义5个大臣
int ministerNum = 5;
for (int i = 0; i < ministerNum; i++) {
Emperor emperor = Emperor.getInstance();
System.out.print("第" + (i + 1) + "个大臣参拜的是:");
emperor.say();
}
}
}