自定义流水号。

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());
        
        
    }
}

 

posted @ 2014-09-05 12:27  harry_ma  阅读(497)  评论(0编辑  收藏  举报
 aa
    部分内容来自网络,如有异议,请联系我.     


      成绩来自坚持, 灵感来自激情。

                                                               感谢父母和亲朋好友的爱与支持!