//恶汉式,可以在多线程环境下使用。但是会过早地创建实例,从而减低内存的使用效率
class Solution {
/**
* @return: The same instance of this class every time
*/
private Solution(){};
public static Solution instance = new Solution();
public static Solution getInstance() {
// write your code here
return instance;
}
};
class Solution {
/**
* @return: The same instance of this class every time
*/
private Solution(){};
private static Solution instance = null;
public static Solution getInstance() {
// write your code here
if(instance == null){
instance = new Solution();
}
return instance;
}
};
//懒汉式改进1。在getInstance方法上加同步。每次通过属性Instance得到单例都会去同步。而同步非常耗时。
class Solution {
/**
* @return: The same instance of this class every time
*/
private Solution(){};
private static Solution instance = null;
public static synchronized Solution getInstance() {
// write your code here
if(instance == null){
instance = new Solution();
}
return instance;
}
};
class Solution {
/**
* @return: The same instance of this class every time
*/
private Solution(){};
private static Solution instance = null;
public static Solution getInstance() {
// write your code here
if(instance == null){
synchronized(Solution.class){
if(instance == null){
instance = new Solution();
}
}
}
return instance;
}
};