码迷,mamicode.com
首页 > 其他好文 > 详细

自定义流水号。

时间:2014-09-05 12:54:31      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   java   ar   for   div   sp   

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
/**
 * 
 * @author Phonnie
 *
 */
public class StreamId {
     
    private static final int MAX_VALUE=9999;
    private static final String FORMAT = "yyMMdd";
    private static final Format DF= new SimpleDateFormat(FORMAT);
    private static final byte[] lock = new byte[0];
    private String prefix = null;
    private Date date = null;
    private int number=1;
    private static Map<String, StreamId> map = new HashMap<String, StreamId>();
     
    private StreamId(String prefix,Date date){
        this.prefix = prefix;
        this.date = date;
    }
     
    public static StreamId newInstance(String prefix){
        Date date = new Date();
        return newInstance(prefix,date);
    } 
     
    public static StreamId newInstance(String prefix,Date date){
        StreamId o = null;
        synchronized (lock) {
            String key = getKey(prefix, date);
            if(map.containsKey(key)){
                o = map.get(key);
                int number = o.getNumber();
                if(number<MAX_VALUE){
                    o.setNumber(number+1);
                }else {
                    o.setNumber(1);
                }
                 
            } else {
                 o = new StreamId(prefix,date);
                 map.put(key, o);
            }
        }
        return o;
    }
     
     
     
    private static String getKey(String prefix,Date date){
        return prefix+format(date);
    }
 
    private static String format(Date date){
        return DF.format(date);
    }
     
    public String toString(){
        return  prefix+ format(date) + String.format("%04d", number);
    }
 
    public void setNumber(int number) {
        this.number = number;
    }
 
    public int getNumber() {
        return number;
    }
    
    public static void main(String[] args){
        StreamId sid=newInstance("AA") ;
        System.out.println("StreamId.main().sid="+sid.toString());
        StreamId sida=newInstance("AA") ;
        System.out.println("StreamId.main().sid="+sida.toString());
        
        
    }
}

 

自定义流水号。

标签:style   blog   color   os   java   ar   for   div   sp   

原文地址:http://www.cnblogs.com/harry335/p/3957807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!