среда, 25 января 2017 г.

Java 8. Execute Around Method pattern.

After reading Venkat Subramaniam book on Java 8 I was impressed with Execute Around Method pattern.
Execute Around Method pattern is useful when the pre- and post-operations have to be guaranteed and the usage of the instance has to be rather narrow and enforced.
Here is the example:
package ru.chernykh.java8;

import java.util.function.Consumer;
public class UsefulResource {
    private UsefulResource() {
        System.out.println("Instantiate resource");
    }
    private void close() {
        System.out.println("close resource");
    }
    public void operator(){
        System.out.println("execute logic");
    }
    public static void process(Consumer<UsefulResource> block) {
        UsefulResource usefulResource = new UsefulResource();
        try {
            block.accept(usefulResource);
        } finally {
            usefulResource.close();
        }
    }

    public static void main(String[] args) {
        UsefulResource.process(usefulResource -> {
            usefulResource.operator();
        });
    }
}


And the output is:
Instantiate resource
execute logic
close resource


Also, more information can be found in his publication at http://www.oracle.com/technetwork/articles/java/architect-10things-2266262.html.