您的位置:首页 > 编程语言 > Java开发

java单例模式生成数据库主键

2016-04-26 10:20 507 查看
先简单介绍一下单例模式:单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

即单例模式有一下三个特点:

1.单例类只能有一个实例。

2.单例类必须自己创建自己的唯一实例。

3.单例类必须给所有其他对象提供这一实例。

简单介绍完单例模式之后就来开始我们的代码吧~~~

创建一个生成主键的工具类:

/**
*
* 生成主键的工具类
* 主键的格式为:当前时间+0~9
*
*/
public class IdUtils {

private static IdUtils instance = null;
private static final long COUNT_SUM = 10;
private static long lastTime = System.currentTimeMillis();
private static short currentCount = 0;

private IdUtils() {
}

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

/**
* 用来产生唯一id
*
* @return
*/
public synchronized String getUID() {
if (currentCount == COUNT_SUM) {
boolean done = false;
while (!done) {
long nowTime = System.currentTimeMillis();
if (nowTime == lastTime) {
try {
Thread.sleep(1);// 可以保证当前得到的时间和上一次的时间不一致
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
continue;
} else {
lastTime = nowTime;
currentCount = 0;
done = true;
}
}
}
return lastTime + "" + (currentCount++);
}

}


接下来测试一下我们的工具类~~

public class demo {

public static void main(String[]args){
for(int i=0;i<20;i++){
System.out.println(IdUtils.getInstance().getUID());
}
}
}


输出结果:



输出成功~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 单例模式