A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 张凡 中级黑马   /  2013-9-8 17:06  /  1121 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

以下代码怎么说明延迟加载和单例设计模式
public class Test8{
       
        static class People{
                private String name;
                private String sex;
                private int age;
                private People(String name,String sex,int age){
                        super();
                        this.name=name;
                        this.sex=sex;
                        this.age=age;
                }
                public static People p=null;
                public static People getPeople(){
                        synchronized (People.class){
                                if(p==null){
                                        p=new People("zhangfan","女",22);
                                }
                        }
                        return p;
                }
                 public String toString() {  
                      return "姓名:"+name+"      年龄: "+age;  
              }
        }
        public static void main(String[] args) {  
                People p1=People.getPeople();  
                People p2=People.getPeople();  
                People p3=People.getPeople();  
        System.out.println(p1);   
        System.out.println(p2);  
        System.out.println(p3);  
        
    }  
}

评分

参与人数 1技术分 +1 收起 理由
杨增坤 + 1

查看全部评分

1 个回复

倒序浏览
public class Test8{
        
        static class People{
                private String name;
                private String sex;
                private int age;
                private People(String name,String sex,int age){//构造方法私有化,只能子在本类中对此类进行实例对象,在其他的类中不能对类进行实例化,然后通过创建方法返回在本类中实例的对象。这就是单例设计模式,
                        super();
                        this.name=name;
                        this.sex=sex;
                        this.age=age;
                }

                public static People p=null; //首先给声明一个对象,,但是实例化,给其一个空值。
                public static People getPeople(){
                        synchronized (People.class){
                                if(p==null){
                                        p=new People("zhangfan","女",22);//在方法中对声明的对象,进行实例化,在判断条件成立的前提下。只要类一加载,对象不会实例化,必须调用获得对象的方法才能实例化此对象,这就是延迟加载
                                }
                        }
                        return p;
                }

                 public String toString() {  
                      return "姓名:"+name+"      年龄: "+age;  
              }
        }
        public static void main(String[] args) {  
                People p1=People.getPeople();  
                People p2=People.getPeople();  
                People p3=People.getPeople();  
        System.out.println(p1);   
        System.out.println(p2);  
        System.out.println(p3);  
        
    }  
}
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马