Sunday, July 1, 2007

A Java Builder Pattern

There's a Builder pattern that Joshua Bloch has briefly described in a couple of his "Effective Java Reloaded" sessions at Java One. This Builder is not necessarily a replacement for the original design pattern. The problems this Builder pattern can solve are too many constructors, too many constructor parameters, and over use of setters to create an object.


Here are some examples of the pattern in use. These examples create various Widgets with two required properties and several optional ones -




Widget x = new Widget.Builder("1", 1.0).
model("1").build();
Widget y = new Widget.Builder("2", 2.0).
model("2").manufacturer("222").
serialNumber("12345").build();
Widget z = new Widget.Builder("3", 4.0).
manufacturer("333").
serialNumber("54321").build();


The basic idea behind the pattern is to limit the number of constructor parameters and avoid the use of setter methods. Constructors with too many parameters, especially optional ones, are ugly and hard to use. Multiple constructors for different modes are confusing. Setter methods add clutter and force an object to be mutable. Here is an class skeleton of the pattern -



public class Widget {
public static class Builder {
public Builder(String name, double price) { ... }
public Widget build() { ... }
public Builder manufacturer(String value) { ... }
public Builder serialNumber(String value) { ... }
public Builder model(String value) { ... }
}

private Widget(Builder builder) { ... }
}


Notice that Widget has no public constructor and no setters and that the only way to create a Widget is using the static inner class Widget.Builder. Widget.Builder has a constructor that takes the required properties of Widget. Widget's optional properties can be set using optional property methods on the Widget.Builder. The property methods of Widget.Builder return a reference to the builder so method calls can be chained.


A really nice feature of this pattern is the ability to do pre-creation validation of an object state. When setters are used to set object state during creation it is virtually impossible to guarantee that object has been properly created.


Here is the full source for Widget and its Builder -



public class Widget {
public static class Builder {
private String name;
private String model;
private String serialNumber;
private double price;
private String manufacturer;

public Builder(String name, double price) {
this.name = name;
this.price = price;
}

public Widget build() {
// any pre-creation validation here
Widget result = new Widget(name, price);
result.model = model;
result.serialNumber = serialNumber;
result.manufacturer = manufacturer;
return result;
}

public Builder manufacturer(String value) {
this.manufacturer = value;
return this;
}

public Builder serialNumber(String value) {
this.serialNumber = value;
return this;
}

public Builder model(String value) {
this.model = value;
return this;
}
}

private String name;
private String model;
private String serialNumber;
private double price;
private String manufacturer;

/**
* Creates an immutable widget instance.
*/
private Widget(String name, double price) {
this.name = name;
this.price = price;
}

public String toString() {
return super.toString() + " {"
+ "name="
+ getName()
+ " model="
+ getModel()
+ " serialNumber="
+ getSerialNumber()
+ " price="
+ getPrice()
+ " manufacturer="
+ getManufacturer()
+ "}";
}

public String getManufacturer() {
return manufacturer;
}

public String getModel() {
return model;
}

public String getName() {
return name;
}

public double getPrice() {
return price;
}

public String getSerialNumber() {
return serialNumber;
}
}


Notice that Widget's private constructor takes the required properties and that the Builder sets the optional properties. Another thing to note is that widget is an immutable object as implemented.

240 comments:

«Oldest   ‹Older   201 – 240 of 240
Singapore citizenship said...

amazing site for ranking site as Mobile Phones

Fubotv Activate said...

You can watch all the live streaming TV shows on the internet using a FuboTv with more than 180 channels. Its packages is made such that you can get all the channels right from your device less than 5 minute after connect it. This is the best package that gives you hundreds of TV channels online. fubo.tv/Connect

janvi verma said...

I will definitely use this information in the very near future.

hr services company

hr services

Simran said...

thanks for providing such a great article, this article very helps full for me, a lot of thanks

online education management system

learning management solutions

Ajaypal Singh said...

"This is really interesting, you are such a great blogger. Visit Royal Digitech for creative and professional website design and Digital Marketing in Sirsa
and Also get Digital Marketing Course in Sirsa
"

Ajaypal Singh said...

"Thanks for provide great informatic and looking beautiful blog, really nice required information & the things i never imagined and i would request, wright more blog and blog post like that for us. Thanks you once agian

Free Classified in India"

AWM Software Solution said...

Much thanks to you for setting aside the effort to compose this blog entry. Much appreciated, entirely significant data. I currently have a reasonable thought on what's going on with this Now read this if you want to Hire Full Stack Developer

daisoftware said...


I’m glad to find another amazing app development blogger.
meal-kit delivery service

Anonymous said...

Now, you can counsel your problems with our dedicated and certified QB pro counselors at QuickBooks Customer Support Phone Number -Nevada USA+1(888) 711-8718. Give us a speedy call at our QuickBooks Customer Support Phone Number -Nevada USA+1(888) 711-8718 to fix your errors.

hunk tv said...

Great! Thanks for sharing this kind of information it’s really very nice and useful for me.
Website Designing Company in Dwarka

Anonymous said...

When suffering from errors in QuickBooks, a professional consultant can help you. our experts can help troubleshoot the issues at QuickBooks Customer Support Phone Number - Minnesota+1(866) 898-9639.

Jobi Johnson said...

It was not first article by this author as I always found him as a talented author.Girlboss Jacket

SREEJITHA said...

Planning to start taxi app?
Planning to start your own taxi business or already have one that you want to grow? Let’s connect and discuss how taxi booking app development grows your business worldwide.


https://cabture.lilacinfotech.com/

Satta King Records said...

Get instant Satta king 2021 fast live results on Sattakingrecords.com. And you can check all new updates regarding all satta games Everyone can see here our favourite Satta results like Satta Matka online games char, game,gali satta chart 2021 and Satta tricks of satta king games, Delhi Satta Bazaar, , Satta king results,satta king , Satta king online games, Faridabad Satta chart, Disawar Satta game, Gali Satta king, and many more game results

Aman Sharma said...

It's an impressive blog post where I have found influenced knowledge which helped me lot in my passion check for more information Blog sites thanks for providing blog post with us.

Debay1 said...

Very informative content. Visit Clinica Health for gallbladder surgeon in kolkata.

eddielydon said...

I am very much pleased with the contents you have mentioned. I wanted to thank you for this great article. arthur morgan winter coat

janvi verma said...

thanks for providing such a great article, this article is very help full for me, a lot of thanks sir
hr support
hr company

Mark Watson said...

403 Forbidden Wi-Fi issues happens when the web page that you are trying to open in web browser is resource that you are not allowed to access. If you face 403 forbidden WiFi error then that’s the HTTP status code that your webserver uses to describe the kind of error. You can usually deal with the error by following the steps mentioned properly.

gurusattaking said...

Satta matka , in particular, is a game that involves betting on various horses in the hopes of winning the satta matka jackpot . This game is very popular in among different classes of people in india.Different class of peoples can check our game result on our official website cm satta

john said...

Very nice blog. I am very impressed this blog. I read very carefully and found some good thoughts in this blog. Thanks...

Coinbase Pro Login
Metamask Login
Coinbase Pro Login
Coinbase Pro Login
Coinbase Pro Login
Coinbase Pro Login
Coinbase Pro Login
Coinbase Pro Login
Coinbase Pro Login

kashif said...

i am a professional web blogger so visit my website link is given below!
softtakes
Java Development Kit for Windows
MEGAsync Crack
Zoom Meeting PC for Windows
Adobe Premiere Pro for Windows CC

Driver Booster for Windows
Windows 7 Ultimate Free Download
Nox App Player for Windows
videoprocvlogger4.1
Adobe Photoshop

Allied Safety Equipments Pvt. Ltd. said...

This is the best topic and I like your blog So I will say you that pls continue this bcoz we need more posts like this type of blog.

petzl HELMETS Vertex price in Mumbai
Petzl DESCENDERS GRIGRI price in Mumbai
Petzl PULLEY Tandem price in Mumbai

Aptron Noida said...

Catia 6 Weeks Summer Training In Noida

jhon wicky said...

colourist logo That is an Great Content

George Mark said...

Thank you very much for this great post. Hart Foundation Jacket

First Copy Watches Mumbai said...

This type of is apparently absolutely outstanding.
These kinds of tiny fact is made making use of wide variety regarding certification know-how. My partner and i favour the theory much.

Replica Watches India said...

You make so many great points here that I read your article a couple of times.
Your views are in accordance with my own for the most part. This is great content for your readers.

Replica Watches India

Anonymous said...

심심출장샵
제주콜걸
제주콜걸
제주콜걸
제주콜걸
제주콜걸
총판출장샵

Online Women Clothing Shop said...

Nice Blog. Buy Glitter Plisse dress is an amazing glittery party dress. It is perfect for any special occasion.

Dwarka Expressway Project said...

Great post! Thanks for posting this. We invite you to visit at our website Luxury Projects on Dwarka Expressway

Johnwintson said...


Excellent breakdown of the Java Builder Pattern! This well-structured explanation makes the concept crystal clear. By the way, I also appreciate how this pattern can be applied to creating a barebones server for efficient resource allocation. Thanks for sharing such valuable insights!

Apprise said...

Amazing Post!

Empowering Digital Dreams: We are an innovative app development company dedicated to turning ideas into immersive and functional mobile experiences.Mobile App Development Company in Noida | Top App Developers in Noida With a passion for cutting-edge technology, we craft solutions that redefine user engagement and drive businesses forward.

Getting Payment Gateways in Europe said...

Dive into a seamless financial frontier with the credit card processing ! Experience swift transactions, unrivaled security, and unparalleled convenience with #WebPays. This cutting-edge solution redefines the way you handle payments, unlocking a new era of efficiency. Say goodbye to hassles and hello to a future where every transaction is a breeze.

ITIO Innovex said...

Discover seamless transactions with the White Label Payment Gateway at ITIO . Tailored solutions empower your brand while ensuring security and flexibility. Join the revolution in payment processing, offering customizable interfaces and advanced features to enhance your business's digital transactions.

Ekaasha Technologies said...

Thanks for sharing such amazing content,
Best Digital Marketing Company in Varanasi

Gregory Homer said...

An enterprise website design agency specializes in developing sophisticated and scalable websites for large businesses. They focus on delivering high-performance, secure, and user-friendly designs tailored to the unique needs of enterprises. By partnering with an "Enterprise Website Design Agency," businesses can enhance their digital presence and achieve their strategic goals effectively.

Shushan said...

If you’re in search of a top mobile app development company in Canada, consider AppStudio. Renowned for its excellence, AppStudio provides high-quality services across various technologies, including Android, iOS, React, IoT, Blockchain, and custom software development.

Gregory Homer said...

WordPress Website Design Service provides tailored, user-friendly websites that are easy to manage, customizable, and scalable, helping businesses create a professional online presence with powerful features and flexibility.

Alfred S. Cavazos said...

Explore a selection of Cheap Homes For Sale In Cape May NJ, ideal for budget-conscious buyers seeking the charm of coastal living. These affordable properties provide a fantastic opportunity to own a slice of paradise without breaking the bank. Enjoy easy access to local attractions, beautiful beaches, and a welcoming community—all at a price you can afford.

«Oldest ‹Older   201 – 240 of 240   Newer› Newest»