KEY生成クラスの2種類の書き方(単多例)
2513 ワード
単例モードの書き方:
マルチパターンの書き方:
個人的に見ると、マルチパターンの書き方がよく使われています.
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();
}
}
個人的に見ると、マルチパターンの書き方がよく使われています.