Created
April 9, 2020 15:23
-
-
Save matsuhiro/bbb81b71c613800ea85ccfbbc8da6e03 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*** | |
* Excerpted from "Functional Programming in Java", | |
* published by The Pragmatic Bookshelf. | |
* Copyrights apply to this code. It may not be used to create training material, | |
* courses, books, articles, and the like. Contact us if you are in doubt. | |
* We make no guarantees that this code is fit for any purpose. | |
* Visit http://www.pragmaticprogrammer.com/titles/vsjava8 for more book information. | |
***/ | |
package fpij; | |
import java.util.function.Supplier; | |
public class Holder { | |
private Supplier<Heavy> heavy = () -> createAndCacheHeavy(); | |
public Holder() { | |
System.out.println("Holder created"); | |
} | |
public Heavy getHeavy() { | |
return heavy.get(); | |
} | |
//... | |
private synchronized Heavy createAndCacheHeavy() { | |
class HeavyFactory implements Supplier<Heavy> { | |
private final Heavy heavyInstance = new Heavy(); | |
public Heavy get() { return heavyInstance; } | |
} | |
if(!HeavyFactory.class.isInstance(heavy)) { | |
heavy = new HeavyFactory(); | |
} | |
return heavy.get(); | |
} | |
public static void main(final String[] args) { | |
final Holder holder = new Holder(); | |
System.out.println("deferring heavy creation..."); | |
System.out.println(holder.getHeavy()); | |
System.out.println(holder.getHeavy()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment