public class StaticField {
private static StringBuffer cache = new StringBuffer();
public static void addString(String s){
cache.append(s).append("/n");
}
public static void clear() {
cache.setLength(0);
}
}
public class Singleton {
private static final Singleton ourInstance = new Singleton();
public static Singleton getInstance() {
return ourInstance;
}
private Singleton() {
}
private StringBuffer cache = new StringBuffer();
public void addString(String s){
cache.append(s).append("/n");
}
public void clear() {
cache.setLength(0);
}
}
static field會(huì)有以下的問題诱告。
不能繼承基類撵枢、實(shí)現(xiàn)接口。
無法進(jìn)行依賴注入精居。不可以通過參數(shù)傳遞到其他方法锄禽。我覺得意義,單例根本不需要傳遞靴姿,單例在哪里都可以直接獲取沃但。
不能在其他類中進(jìn)行測(cè)試(mock)。
如何選擇佛吓?
static成員變量是給不需要狀態(tài)的情況下使用的宵晚,通常只放一堆函數(shù)垂攘,例如Math和其他Utils類。
Singleton更為的靈活淤刃,更容易控制它的狀態(tài)晒他,可以實(shí)現(xiàn)接口,繼承自其他類并給其他類繼承钝凶。
https://stackoverflow.com/questions/47325586/singleton-class-vs-static-methods-and-fields
https://stackoverflow.com/questions/519520/difference-between-static-class-and-singleton-pattern