Design Pattern In Practice – Builder Pattern


Builder Pattern

See this code snippnet in Async Http Client project.

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.

See Internal

There are few things you may notice in this example.

  • Separate out config from DefaultAsyncHttpClient.
  • 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:

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:

Design Pattern In Practice – Builder Pattern

log in

Use demo/demo public access

reset password

Back to
log in
Choose A Format
Personality quiz
Trivia quiz
Poll
Story
List
Meme
Video
Audio
Image