Skip to content

Instantly share code, notes, and snippets.

@adohe-zz
Created February 16, 2014 16:26
Show Gist options
  • Save adohe-zz/9036797 to your computer and use it in GitHub Desktop.
Save adohe-zz/9036797 to your computer and use it in GitHub Desktop.
Lazy initialization
Lazy initialization has two objectives:
1. delay an expensive operation until it's absolutely necessary
2. store the result of that expensive operation, such that you won't need to repeat it again.
To avoid a NullPointerException, a class must self-encapsulate fields that have lazy initialization.
That is, a class cannot refer directly to such fields, but must access them through a method.
The hashCode method of an immutable Model Object is a common candidate for lazy initialization.
public final class Lazyer {
private int mId;
private String mName;
private int hashCode;
private List<String> mPigs;
public Lazyer() {
mId = 1;
mName = "beep";
}
public List<String> getPigs() {
if(mPigs == null) {
List<String> pigs = new ArrayList<>();
****
mPigs = pigs;
}
return mPigs;
}
public int hashCode() {
if(hashCode == 0) {
****
hashCode = HashCodeUtil.hashCode(/**what ever you want**/);
}
return hashCode;
}
}
public final class Printers {
private static List<PrintService> services;
void print(String someThing, PrintService printService) {
}
List<PrintService> getAvailablePrintService(PrintAttributeSet attrs) {
if(services == null) {
//Do something with attribute set to get the printers
services = PrintServiceLookup.lookupAvaiableService(attrs);
}
return services;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment