Java lazy initialization example 2016-12-20 07:42

Lazy initialization pattern is similar to lazy initialization singleton. The key point of lazy initialization is "no need no create". The sample of code is like following.

public class Product {
    private String name;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    private static final Map<String, Product> types = new HashMap<>();

    private Product(String name) { = name;

    public static Product getProductByName(String productName) {
        if (!types.containsKey(productName)) {// here is not thread-safe, I don't want to talk it in this blog
            types.put(productName, new Product(productName));
        return types.get(productName);

    public String toString() {
        return "Product{" +
                "name='" + name + '\'' +

    public static void showAllProduct() {

The code of client is like following. Display all products after getting product.

public class Client {
    public static void main(String[] args) {
        Product productA = Product.getProductByName("A");
        Product productB = Product.getProductByName("B");

The output is like following.

{A=Product{name='A'}, B=Product{name='B'}}