Examples of creational patterns in Java

Read more about the creational design patterns.

builder pattern

The builder pattern allows create object step by step. For example StringBuilder class.

public class Demo {
    private int field1;
    private int field2;
    ...
    private int fieldN;
   
    // dissallow create object via constructor 
    // from outside of the class
    private Demo() {}

    public static class DemoBuilder(){
        private Demo demo = new Demo();
        
        public DemoBuilder setField1(int v) {
            demo.field1=v;
            return this;
        }
        ...
        
        public Demo build(){
            // check is object was initialized properly
            ...
            return demo;
        }
    }		
}

Demo demo = new Demo.DemoBuilder()
    .setField1(v1)
    .setField2(v2)
        ...
    .setFieldN(vn)
    .build();

singleton pattern

The singleton is used when you need only one instance of a class in an application.

class DemoSingleton{
        
    // dissallow create object via constructor 
    // from outside of the class
    private DemoSingleton() {}
    ...
    
    private static volatile DemoSingleton instance = null;

    public static DemoSingleton getInstance() {
          
        if (instance == null) synchronized (DemoSingleton.class) {
            if(instance==null){
                instance = new DemoSingleton();
            }
        }

        return instance;
     }
}
class DemoSingleton{
    // dissallow create object via constructor 
    // from outside of the class
    private DemoSingleton() {}
    ...
    
    private static DemoSingleton instance = DemoSingleton();

    public static DemoSingleton getInstance() {
        return instance;
    }
}
enum DemoSingleton{
   INSTANCE;
   ...
}
class DemoSingleton{
    // dissallow create object via constructor 
    // from outside of the class
    private DemoSingleton() {}
    ...

    private static DemoSingleton instance = null;

    public static DemoSingleton getInstance() {
        if(instance==null){
            instance = new DemoSingleton();
        }
        return instance;
    }
}
class DemoSingleton{
    // dissallow create object via constructor 
    // from outside of the class
    private DemoSingleton() {}
    ...
    
    private static DemoSingleton instance =null;

    public static synchronized DemoSingleton getInstance() {
        if(instance==null){
           instance = new DemoSingleton()
        }
        return instance;
    }
}