//懒汉式,就是创建一个
class LaySingleton{
public static LaySingleton instanle = null;
public LaySingleton() {
// TODO Auto-generated constructor stub
}
public static synchronized LaySingleton getinstance(){
if(instanle == null)
{
instanle = new LaySingleton();
}
return instanle;
}
}
//饿汉式,每次都创建,不需要加synchronized 天生线程都安全的.
class LaySingleton{
public static LaySingleton instanle = new LaySingleton();
public LaySingleton() {
// TODO Auto-generated constructor stub
}
public static LaySingleton getinstance(){
return instanle;
}
}
class LaySingleton{
public static LaySingleton instanle = null;
public LaySingleton() {
// TODO Auto-generated constructor stub
}
public static synchronized LaySingleton getinstance(){
if(instanle == null)
{
instanle = new LaySingleton();
}
return instanle;
}
}
//饿汉式,每次都创建,不需要加synchronized 天生线程都安全的.
class LaySingleton{
public static LaySingleton instanle = new LaySingleton();
public LaySingleton() {
// TODO Auto-generated constructor stub
}
public static LaySingleton getinstance(){
return instanle;
}
}
本文详细介绍了单例设计模式中的两种实现方式:懒汉式与饿汉式。懒汉式通过同步方法确保实例唯一并在首次调用时创建实例;而饿汉式则在类加载时就创建实例,天然具备线程安全性。
232

被折叠的 条评论
为什么被折叠?



