寫兩種常用的單例模式實現,對比一下兩種方式的實現有什麼差異:
No1:
public class Test {
private static Test instance = null;
public static Test getInstance()
{
synchronized (Test.class) {
if (instance == null) {
instance = new Test();
}
}
return instance;
}
}
No2:
public class Test {
private static Test instance = null;
public synchronized static Test getInstance()
{
if (instance == null) {
instance = new Test();
}
return instance;
}
}