赞
踩
- package cn;
-
- public class DanEHan {
- private static DanEHan danEHan=new DanEHan();
- private DanEHan(){}
- public static DanEHan getInstance(){
-
- return danEHan;
- }
-
-
- public static void main(String[] args) {
- DanEHan d1=DanEHan.getInstance();
- DanEHan d2= DanEHan.getInstance();
- System.out.println(d1==d2);
- }
- }
- package cn;
-
- public class DanLanHan {
- private static DanLanHan danLanHan;
- private DanLanHan(){}
-
- public static synchronized DanLanHan getInstance(){
- if(danLanHan==null){
- danLanHan=new DanLanHan();
- }
- return danLanHan;
- }
-
- public static void main(String[] args) {
- DanLanHan d1=DanLanHan.getInstance();
- DanLanHan d2=DanLanHan.getInstance();
- System.out.println(d1==d2);
- }
- }
单例模式就是每次创建对象都是同一个对象,可以看出懒汉式是线程安全的,通过处理判断是否继续new对象有对象就返回原来的对象,所以推荐使用懒汉式
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。