单例设计模式简单分为 懒汉模式 和 饿汉设计模式:
一, 单例设计模式的基本步骤:
1,私有化构造函数
2,声明一个本类的类对象,
3,提供一个静态的公共函数来获取本类对象
二,懒汉单例设计模式
class LazySingle{
private LazySingle(){}
private Person p = new Person();
public static Person getPerson(){
return p;
}
}
三,饿汉单例设计模式
class HunSingle{
private HunSingle(){}
private Person p ;
public static Person getPerson(){
if(p==null){
synchronized("suo"){
if(p==null){
p = new Person();
return p;
}
else{
return p;
}
}
}
return p;
}
}
饿汉设计模式存在线程安全问题,应该要加锁。