Builder is like a factory method that is in class scope and to prepare you the instance of the class. The difference is all about how to create the instance. If an instance has many different ways to be composed of, you probably don’t want to code all the possible variations of constructors, right? However, if you simply use setters, you may not have a way to make sure the instance is composed correctly before it is in use. Then, Builder Pattern is a good tool for you. It has all setters return the Builder instance (normally inner class of the subject class). So, the setter operations can be chained together with a final build() to return the parent class instance. For properties not yet set, default will be used.

The config is created thru builder pattern and it is immutable once constructed.

Use default for some properties that is not manipulated by developer.

For the DefaultAsyncHttpClient, it has default constructor if you use want to use the default settings. To do that, you can see the code below:

1

2

3

4

5

6

public DefaultAsyncHttpClient(){

this(newDefaultAsyncHttpClientConfig.Builder().build());

}

Another Example – ThreadFactory

By default, JVM thread dump gives you the naming like pool-N-thread-M, where N stands for pool sequence number and M stands for thread sequence number of the pool. If you want to override it or have threads as daemon, you can use Guava’s ThreadFactoryBuilder as below:

1

2

3

4

5

6

7

8

9

10

importcom.google.common.util.concurrent.ThreadFactoryBuilder;

final ThreadFactory threadFactory=newThreadFactoryBuilder()

.setNameFormat("Orders-%d")

.setDaemon(true)

.build();

final ExecutorService executorService=Executors.newFixedThreadPool(10,threadFactory);