среда, 22 февраля 2012 г.

Паттерн Прокси(Proxy). Пример кода

public interface Image {
    public String get(String imgName);
}

public class LargeImage implements Image {
    @Override
    public String get(String imgName) {
        System.out.println("some expensive operation for loading image");
        return String.format("image with name \"%s\"", imgName);
    }
}

public class ImageProxy implements Image {
    
    private Image realImage = new LargeImage();
    private Map loadedImages = new HashMap();
    
    @Override
    public String get(String imgName) {
        if (loadedImages.get(imgName) != null) {
            return loadedImages.get(imgName);
        } else {
            String image = realImage.get(imgName);
            loadedImages.put(imgName, image);
            return image;
        }
    }
}

public class ImagesTester {
    public static void main(String[] args) {
        Image image1 = new ImageProxy();
        Image image2 = new LargeImage();
        System.out.println(image1.get("Flowers.jpg"));
        System.out.println(image1.get("Flowers.jpg"));
        System.out.println(image1.get("Flowers.jpg"));
        
        System.out.println(image2.get("Sky.jpg"));
        System.out.println(image2.get("Sky.jpg"));
    }
}
/**
 * Output:
 * some expensive operation for loading image
 * image with name "Flowers.jpg"
 * image with name "Flowers.jpg"
 * image with name "Flowers.jpg"
 * some expensive operation for loading image
 * image with name "Sky.jpg"
 * some expensive operation for loading image
 * image with name "Sky.jpg"
 */

суббота, 18 февраля 2012 г.

Особенность использования блока finally

Блок finally исполняется даже после операторов break, continue и return. Но если внутри блока finally выскочит исключение или будет вызвана команда return, всё что будет после в этом блоке не выполнится:

try {
    throw new Exception("Some exception");
} catch (Exception e) {
    System.out.println(e.getMessage());
} finally {
    String t = null;
    t.contains("string");
    System.out.println("Never printed");
}
/**
 * Output:
 * Some exception
 * Exception in thread "main" java.lang.NullPointerException
 * at test.TestFinally.main(TestFinally.java:18)
 */