RSS Feed for This PostCurrent Article

Design Pattern in Java 101 – Lazy Load Part II

Download Sample Code

This is Part II of the previously described Lazy Load pattern.

value holder
A value holder is used as a generic Lazy Load. It is an object that wraps some other object. To get the underlying object you ask the value holder for the value, and the first access will pull the data from the database.

E.g., First define the base DomainObject

package valueholder;

public class DomainObject {
}

Both Student and Course inherits it.

package valueholder;

import java.util.List;

public class Student extends DomainObject {
    private Long id;
    private ValueHolder courses;

    public Student(Long id) {
        this.id = id;
    }

    public List getCourses() {
        return (List)courses.getValue();
    }

    public void setCourses(ValueHolder courses) {
        this.courses = courses;
    }
}

package valueholder;


public class Course extends DomainObject {
}

Then define the ValueLoader interface.

package valueholder;

public interface ValueLoader {
    Object load();
}

ValueHolder is defined to return the generic object.

package valueholder;

public class ValueHolder {
    private Object value;
    private ValueLoader loader;

    public ValueHolder(ValueLoader loader) {
        this.loader = loader;
    }

    public Object getValue() {
        if (value == null) value = loader.load();
        return value;
    }  
}

StudentMapper is defined.

package valueholder;

import java.util.ArrayList;

public class StudentMapper {

    protected DomainObject doLoad(Long id) {
        Student student = new Student(id);
        student.setCourses(
                new ValueHolder(new CourseLoader(id)));
        return student;
    }

    public static class CourseLoader implements ValueLoader {
        private Long id;

        public CourseLoader(Long id) {
            this.id = id;
        }

        public Object load() {
            // Return dummy empty list
            return new ArrayList(2);
        }
    }
}


Trackback URL


RSS Feed for This Post1 Comment(s)

  1. Kelly Compton | Apr 22, 2008 | Reply

    tubercularia slopy dobrao figuline lactigenic consentant vesicoprostatic finify
    Technozid
    http://es.wikipedia.org/wiki/Perro

Sorry, comments for this entry are closed at this time.