/**
* 单例模式:
* 关键:
* 获取对象只有一个实例,创建单例有两种方法:一种饿汉式(一开始就创建),一种懒汉式(获取对象时创建)
* @author zbl
*
*/
public class SingleCustomer {
public static void main(String[] args) {
Single1 single1 = Single1.getInstance();
Single2 single2 = Single2.getInstance();
}
}
//饿汉式
class Single1{
private static Single1 single1 = new Single1();
private Single1(){};
public static Single1 getInstance(){
return single1;
}
}
//懒汉式
class Single2{
private static Single2 single2 = null;
private Single2(){}
public static Single2 getInstance(){
if(single2==null){//判断是否为空
synchronized (Single2.class) {//应对多线程
if(single2==null){//当多个进程通过了判断1,有次判断过滤确保只有一个进程实例化了对象
single2 = new Single2();
}
}
}
return single2;
}
}
17.单例模式
最新推荐文章于 2023-02-20 20:09:38 发布