`
kinkding
  • 浏览: 147601 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

KEY生成类的两种写法(单多例)

    博客分类:
  • JAVA
阅读更多

单例模式写法:

package kg;

import java.util.HashMap;
import java.util.Map;

public class KeyGene {
	private static KeyGene instance;
	private Map<String, Key> cache;
	/** 缓存大小 */
	public static int SIZE = 10;

	private KeyGene() {
		cache = new HashMap<String, Key>();
	}

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

	public int getNextKey(String keyName) {
		Key key = cache.get(keyName);
		if (key == null) {
			key = new Key(SIZE, keyName);
			cache.put(keyName, key);
		}
		return key.getNext();
	}

	public static void main(String[] args) {
		KeyGene kg = KeyGene.getInstance();
		int key = kg.getNextKey("goodjob");
	}
}

class Key {
	private int max;
	private int size;
	private int next;
	private String name;

	public Key(int size, String name) {
		this.size = size;
		this.name = name;
		dbOperate();
	}

	public synchronized int getNext() {
		if (next > max) {
			dbOperate();
		}
		return next++;
	}

	private void dbOperate() {
		// 执行数据库操作
		// if next >1 then
		// max = next+size;
		// update key_store set value=max where code = this.name
		// else
		// next = 1;
		// max = next+size;
		// insert into key_store(code,value)values(this.name,this.max);
	}
}

 

 

多例模式写法:

package kg;

import java.util.Map;

public class KeyGene2 {
	private static Map<String, KeyGene2> cache;
	public static int SIZE = 10;
	private Key key;

	private KeyGene2(String keyName) {
		key = new Key(SIZE, keyName);
	}

	public static KeyGene2 getInstance(String keyName) {
		KeyGene2 kg = cache.get(keyName);
		if (kg == null) {
			kg = new KeyGene2(keyName);
			cache.put(keyName, kg);
		}
		return kg;
	}

	public int getNextKey() {
		return key.getNext();
	}

	public static void main(String[] args) {
		KeyGene2 kg = KeyGene2.getInstance("goodjob");
		int key = kg.getNextKey();
	}
}

 

 

就我个人来看,多例模式写法更常用些。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics