在标准的23中设计模式中单例模式是应用最多的。
(1) 立即加载/饿汉模式
立即加载就是使用类的时候已经将对象创建完毕,常见的实现方法就是直接new实例化。
public class MyObject {
// 单利模式饿汉模式
private static MyObject myObject = new MyObject();
private MyObject() {
}
public static MyObject getObject() {
return myObject;
}
}
public class MyThread extends Thread {
@Override
public void run() {
System.out.println(MyObject.getObject().hashCode());
}
}
public class Run {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.start();
t2.start();
t3.start();
}
}
(2) 延时加载/懒汉模式
延时加载就是在调用get()方法时实例才被创建,常见的实现办法就是在get()方法中进行new()初始化。
public class SingleStance {
private static SingleStance singleStance;
private SingleStance() {
}
// 延时加载 单例
public static SingleStance getSingleStance() {
if (singleStance != null) {
} else {
singleStance = new SingleStance();
}
return singleStance;
}
}
public class SingleThread extends Thread {
@Override
public void run() {
System.out.println(SingleStance.getSingleStance().hashCode());
}
}
public class Run {
public static void main(String[] args) {
// TODO Auto-generated method stub
// MyThread t1 = new MyThread();
// MyThread t2 = new MyThread();
// MyThread t3 = new MyThread();
// t1.start();
// t2.start();
// t3.start();
SingleThread t4 = new SingleThread();
SingleThread t5 = new SingleThread();
SingleThread t6 = new SingleThread();
t4.start();
t5.start();
t6.start();
}
}
这两种单例模式的缺点是:在多线程的环境中,延时加载完全不能保证实现地单例模式。修改方法就是在getSingleStance()方法上添加synchronized关键字
(3) SimpleDateFormat非线程安全
类SimpleDateFormat主要负责日期转化与格式化,但是在多线程的环境中,使用此类容易造成数据转换及处理的不准确行,因为SimpleDateFormat类并不是线程安全的。