1. 饿汉式
public class IdGenerator {

    private static final IdGenerator instance = new IdGenerator();

    private IdGenerator() {
    }

    public static IdGenerator getInstance() {
        return instance;
    }

}
  1. 懒汉式
public class IdGenerator {

    private static IdGenerator instance;

    private IdGenerator() {
    }

    public static synchronized IdGenerator getInstance() {
        if (instance == null) {
            instance = new IdGenerator();
        }
        return instance;
    }

}
  1. 双重检测
public class IdGenerator {

    private volatile static IdGenerator instance;

    private IdGenerator() {
    }

    public static IdGenerator getInstance() {
        if (instance == null) {
	    // 此处为类级别的锁
            synchronized (IdGenerator.class) { 
                if (instance == null) {
                    instance = new IdGenerator();
                }
            }
        }
        return instance;
    }

}
  1. 静态内部类
public class IdGenerator {

    private IdGenerator() {
    }

    private static class SingletonHolder {
        private static final IdGenerator instance = new IdGenerator();
    }

    public static IdGenerator getInstance() {
        return SingletonHolder.instance;
    }

}
  1. 枚举
public enum IdGenerator {
    INSTANCE;

    private AtomicLong id = new AtomicLong(0);

    public long getId() {
        return id.incrementAndGet();
    }
}

Q.E.D.


Stay focused and work hard!