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

单例模式写法:

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

 

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值