KEY生成类的两种写法(单多例)
程序员文章站
2022-05-03 23:49:51
...
单例模式写法:
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();
}
}
就我个人来看,多例模式写法更常用些。
推荐阅读