I am a complete newbie when it comes to the use of factory classes and methods, patterns, etc - in fact I first learned of them here on Stackoverflow when browsing Java related questions :-)
In response to a previous question of mine it was suggested that I look into the use of the Builder Pattern in the development of my GUI's and so I am seeking good easily understood examples demonstrating how an application's user interface could be put toghether using this pattern and method-chaining, etc.
Thanks for reading.
Let's see how we can implement builder design pattern in java. First of all you need to create a static nested class and then copy all the arguments from the outer class to the Builder class. We should follow the naming convention and if the class name is Computer then builder class should be named as ComputerBuilder .
Builder pattern builds a complex object using simple objects and using a step by step approach. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. A Builder class builds the final object step by step.
The builder pattern, as the name implies, is an alternative way to construct complex objects. This pattern should be used when we want to build different immutable objects using the same object building process.
The builder pattern is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming. The intent of the Builder design pattern is to separate the construction of a complex object from its representation.
There are probably other (and better) examples but here is one.
When working with GridBagConstraints
, one could use this horrible constructor:
public GridBagConstraints(int gridx, int gridy,
int gridwidth, int gridheight,
double weightx, double weighty,
int anchor, int fill,
Insets insets, int ipadx, int ipady)
But I consider it unusable. And people most often end up using the empty constructor and setting the various public attributes to override the defaults values.
As an alternative, one could use a builder, something like this:
somePanel.add(
getContent(),
new ConstraintsBuilder()
.gridLocation(1, 1)
.gridSize(1, 1)
.weight(0.0, 0.0)
.anchor(NORTHWEST)
.build() );
Just an example.
Joshua Bloch's Item 2: Consider a builder is always a good place to start. Regarding GUI development, many layout managers use the builder pattern. A Visual Guide to Layout Managers is a good introduction.
I think "Source Making" does a nice job of introducing design patterns (as well as UML, Antipatterns and Refactoring). You may want to check the site out.
You can read about the Builder here: Source Making: Builder Design Pattern
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With