使用枚舉緩存SimpleDateFormat實例

在我們的項目中,時常需要對日期進行操作,因此常常會大量的產生SimpleDateFormat實例,但是,

1.SimpleDateFormat的初始化其實是比較耗費性能的,

2.這個日期的格式大部分都是那麼幾種,諸如yyyy-MM-dd HH:mm:ss,yyyy-MM-dd等等

3.SimpleDateFormat是線程不安全的,所以我們又不得不對每個格式都至少有一個 實例

綜上幾點,我們可以使用一個Map來將這些實例進行緩存,與其格式一一對應。代碼如下:

package com.test.redis.test;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

public class CacheUtil {
	private final static Map<String, SimpleDateFormat> dateFormatMap;
	static{
		dateFormatMap = new HashMap<String, SimpleDateFormat>();
		for (DateFormatCache cache : DateFormatCache.values()) {
			SimpleDateFormat format;
			if (cache.getDescription() == null) {
				format = new SimpleDateFormat();
			}else{
				format = new SimpleDateFormat(cache.getDescription());
			}
			dateFormatMap.put(cache.getDescription(), format);
		}
	}
	public static enum DateFormatCache{
		NormalDateTime("yyyy-MM-dd HH:mm:ss"),
		NormalTime("HH:mm:ss"),
		NormalDate("yyyy-MM-dd"),
		CompactTime("HHmmss"),
		CompactDate("yyyyMMdd"),
		Default(null),
		;
		private String description;
		public String getDescription() {
			return this.description;
		}
		public SimpleDateFormat getFormatter(){
			return dateFormatMap.get(this.description);
		}
		DateFormatCache(String description) {
			this.description = description;
		}
	}
}

測試代碼如下:

	@Test
	public void test(){
		Date date = new Date();
		DateFormatCache[] caches = CacheUtil.DateFormatCache.values();
		for (DateFormatCache dateFormatCache : caches) {
			String format = dateFormatCache.getFormatter().format(date);
			System.out.println(format);
		}
	}

測試結果如下:

2018-04-02 22:45:25
22:45:25
2018-04-02
224525
20180402
18-4-2 下午10:45


這博客寫着寫着,我又發現另外一種更簡單的方法,發現map好像也是多餘的。。。。。尷尬。。

	public static enum DateFormatCache{
		NormalDateTime("yyyy-MM-dd HH:mm:ss"),
		NormalTime("HH:mm:ss"),
		NormalDate("yyyy-MM-dd"),
		CompactTime("HHmmss"),
		CompactDate("yyyyMMdd"),
		Default(null),
		;
		private String description;
		private SimpleDateFormat format;
		public String getDescription() {
			return this.description;
		}
		public SimpleDateFormat getFormatter(){
			return this.format;
		}
		DateFormatCache(String description) {
			this.description = description;
			if (description == null) {
				this.format = new SimpleDateFormat();
			}else{
				this.format = new SimpleDateFormat(description);
			}
		}
	}
這樣子測試結果也是一樣的,代碼還更加簡單了,並且省略了map那一步,性能應該也更好了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章