1.利用枚举类型实现(单多线程均可)
- public enum SingletonWithEnum {
- /**
- * @author boker
- */
- instance;
- public static SingletonWithEnum getInstance() {
- return instance;
- }
- }
原理是:枚举类型当只有一个成员时,就是一个最简单的单例模式实现方式。
Effective Java作者Josh Bloch 提倡这种方式,它不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象,但很少有人这么用,或许是应为enum在jdk1.5之后才出来,大家都已经用习惯用常规的设计模式实现了。
枚举单例模式实例:
package zqd.demo; public class Easy { public static void main(String[] args) { MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); MyThread t3 = new MyThread(); t1.start(); t2.start(); t3.start(); } } class MyThread extends Thread{ @Override public void run() { super.run(); for (int i = 0; i < 5; i++) { System.out.println(MyObject.objectFactory.getObject().hashCode()); } } } enum MyObject{ objectFactory; private Object object; private MyObject(){ object = new Object(); } public Object getObject(){ return object; } }
输出:
37621924 37621924 37621924 37621924 37621924 37621924 37621924 37621924 37621924 37621924 37621924 37621924 37621924 37621924 37621924
可见是一样的,是线程安全的
2.单线程实现(非线程安全,不适用与多线程)
1> 定义一个类(该类最好定义成final类型的可以防止被继承)
2>声明一个private的该类 类型的静态实例成员instance
3>实现一个private的构造函数
4>实现一个public静态方法getInstance(),在其中调用私有构造函数创建该类的一个实例,返回给调用者
代码实现如下:
- public class Singleton {
- /**
- * @author boker
- */
- private static Singleton instance;
- private Singleton() {
- }
- public static Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
- }
3.线程安全的实现方式(适用于多线程,但效率低)
- public class Singleton3 {
- /**
- * @author boker
- */
- private static Singleton3 instance = null;
- private Singleton3() {}
- public static synchronized Singleton3 getInstance() {
- return instance==null?instance=new Singleton3():instance;
- }
- }
4.双重校验锁( 适用于jdk1.5之后)
- public class Singleton4 {
- /**
- * @author boker
- */
- private volatile static Singleton4 instance;
- private Singleton4() {}
- public static Singleton4 getInstance() {
- if (instance==null) {
- synchronized (Singleton4.class) {
- if (instance==null) {
- instance = new Singleton4();
- }
- }
- }
- return instance;
- }
-
- 5、静态内置类实现
- //静态内置类实现
- public class Easy {
public static void main(String[] args) throws ParseException {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.start();
t2.start();
t3.start();
}
}
class MyThread extends Thread{
@Override
public void run() {
super.run();
System.out.println(MyObject.getInstance().hashCode());
}
}
class MyObject{
private static class MyObjectHandler{
private static MyObject myObject = new MyObject();
}
private MyObject(){
}
public static MyObject getInstance(){
return MyObjectHandler.myObject;
}
}