-
Notifications
You must be signed in to change notification settings - Fork 1
Pattern: Builder
justinmann edited this page Mar 17, 2017
·
2 revisions
The builder pattern is a convenient way to allow mutability when assigning constructor values and then convert to immutable when the final object is constructed.
button(
color :'color
text :'string
) { this }
buttonBuilder(
color = colors.red
text = ""
setColor(c'color) {
color = c
this
}
setText(t'string) {
text = t
this
}
build() {
button(
color: color,
text: text
)
}
) { this }
However, if you are primarily using the builder pattern to handle a constructor with many arguments most of which have default values then it is much cleaner to use the default constructor values. They have a special ability to be immutable after construction but mutable during construction:
button(
color: colors.blue
text: "Hello"
) { this }
// The color is modified during construction
b: button(color: colors.white)
// This will fail, because the color is actually immutable, it can only be modified during construction
b.color = colors.green