如果要保证系统里一个类最多只能存在一个实例时,我们就需要单例模式.
public class Singleton{
public static Singleton instance=new Singleton();
//other fields
private Singeton(){}
public static Singleton getInstance(){
return instance;
}
//other methods
}
public class ThreadSafeSingleton{
private volatile static ThreadSafeSingleton instance;
private ThreadSafeSingleton(){};
public static ThreadSafeSingleton getInstance(){
if(instance==null){
synchronisezd(ThreadSafeSingleton.class){
if(instance==null)
instance =new ThreadSafeSingleton();
}
}
return instance;
}
}
时间: 2024-10-22 07:48:14