小知了
一个不神奇的博客
延迟加载一个对象
2017-01-21 20:39:14   阅读1662次


使用对象的前才去实例化对象,这叫延迟加载对象(LazyLoad)。在懒汉单例模式中有用到。代码如下:


class Simple{
    private String s;
    public Simple(String s){
        this.s = s;
    }
    public String toString(){
        return s;
    }
    public void setString(String s){
        this.s = s;
    }
}
 
class Second{
    private Simple simple;
    private String s;
    public Second(String s){
        this.s = s;
    }
    public void check(){
        if(simple == null){
            System.out.println("not init the simple object");
        }else{
            System.out.println("init the simple object");
        }
    }
     
    private Simple lazy(){
        if(simple == null){
            simple = new Simple(s);
            return simple;
        }
        return simple;
    }
     
    public Simple getSimple(){
        return lazy();
    }
     
    public void setSimple(String s){
        lazy().setString(s);
    }
     
    public String toString(){
        return lazy().toString();
    }
}
  
public class Test1 {
 
    public static void main(String[] args) {
         
        Second second = new Second("Init String");
        //此时并没有实例化Simple对象
        second.check();
        // 需要Simple时候才去实例化
        System.out.println(second.getSimple());
        second.check();
        System.out.println(second); // toString() call
        second.setSimple("New String");
        System.out.println(second);
    }
}

输出:

not init the simple object
Init String
init the simple object
Init String
New String

参考《Java编程思想》P126



-----------------------------------------------------
转载请注明来源此处
原地址:#

-----网友评论----
暂无评论
-----发表评论----
微网聚博客乐园 ©2014 blog.mn886.net 鲁ICP备14012923号   网站导航