减少延迟加载图像的代码

Reduce code for lazy loading image

我有很多图片要加载,我希望延迟加载。在这一点上,我用我所有加载的图像写了一个class。

public static ImageIcon binIcon = getBinIcon();
private static ImageIcon getBinIcon() {
    if(binIcon == null) {
        return binIcon = FileManipulation.getImage("img/bin.jpg");
    }
    else {
        return binIcon;
    }
}

public static ImageIcon checkboxIcon = getCheckboxIcon();
private static ImageIcon getCheckboxIcon() {
    if(checkboxIcon == null) {
        return checkboxIcon = FileManipulation.getImage("img/checkbox.png");
    }
    else {
        return checkboxIcon;
    }
}

...

最后我有很多重复代码,我正在寻找减少它的性感方法。

谢谢你的想法!

您可以创建一个接收要加载的图标和文件名的方法:

public static ImageIcon checkboxIcon;
public static ImageIcon binIcon;

private static ImageIcon getCheckboxIcon(ImageIcon icon, String fileName) {
    return icon == null ? FileManipulation.getImage(fileName) : icon;
}

它将允许您以这种方式加载图标:

binIcon = getCheckboxIcon(binIcon, "img/bin.png");
checkboxIcon = getCheckboxIcon(checkboxIcon, "img/checkbox.png");

简单的面向对象——一个class LazyImageIcon extends ImageIcon。然后你甚至可以推迟阅读第一幅画,如果给构造函数正确的图像大小。