我有一個FutureContent類,它只保存一個Future類的靜態引用。我不確定爲什麼這樣做,這意味着現在每個方法調用都不必是靜態的。這是否有另外一個原因呢?爲什麼要以這種方式使用「靜態」類?
//One possible use of Future class
FutureContent.future.deleteContent("test");
public class FutureContent {
public static Future future = new Future();
}
public class Future{
private final Object lock = new Object();
private String str;
private Hashtable content = new Hashtable();
public void addContent(Object key, Object value){
synchronized(lock){
if(content.containsKey(key)){
content.remove(key);
content.put(key, value);
}
else {
content.put(key, value);
}
}
}
public void clearContent(){
content.clear();
}
public void deleteContent(Object key){
if(content.containsKey(key)){
content.remove(key);
}
}
public boolean getBoolean(Object key){
if(!content.contains(key)){
return false;
}
else {
return ((Boolean)content.get(key)).booleanValue();
}
}
public void addBoolean(Object key , boolean value){
Boolean b = new Boolean(value);
synchronized(lock){
if(content.containsKey(key)){
content.remove(key);
content.put(key, b);
}
else {
content.put(key, b);
}
}
}
public Object getContent(Object key){
return content.get(key);
}
public void setString(String str){
synchronized(lock){
this.str = str;
lock.notifyAll();
}
}
public String getString(){
synchronized(lock){
while(this.str == null)
try {
lock.wait();
} catch (InterruptedException e) {
return null;
}
return this.str;
}
}
private JSONObject value;
public void set(JSONObject t){
synchronized(lock){
value = t;
lock.notifyAll();
}
}
public JSONObject get(){
synchronized(lock){
while(value == null)
try {
lock.wait();
} catch (InterruptedException e) {
return null;
}
return value;
}
}
}
單身的所有樂趣,沒有所有那些惱人的訪問控制! – cHao
是的,這只是一個單例(一個非線程安全的,BTW) –