Skip to content

Commit 6bab5f3

Browse files
author
Thomas Gotwig
authored
Make builder pattern more practical (#90)
1 parent 344b5b8 commit 6bab5f3

File tree

1 file changed

+26
-22
lines changed

1 file changed

+26
-22
lines changed

patterns/builder.md

Lines changed: 26 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,48 +2,52 @@
22

33
## Description
44

5-
Construct an object with calls to a builder helper.
6-
5+
Construct an object with calls to a builder helper.
76

87
## Example
98

10-
```rust,ignore
11-
struct Foo {
9+
```rust
10+
#[derive(Debug, PartialEq)]
11+
pub struct Foo {
1212
// Lots of complicated fields.
13+
bar: String,
1314
}
1415

15-
struct FooBuilder {
16+
pub struct FooBuilder {
1617
// Probably lots of optional fields.
17-
//..
18+
bar: String,
1819
}
1920

2021
impl FooBuilder {
21-
fn new(
22-
//..
23-
) -> FooBuilder {
22+
pub fn new(/* ... */) -> FooBuilder {
2423
// Set the minimally required fields of Foo.
24+
FooBuilder {
25+
bar: String::from("X"),
26+
}
2527
}
2628

27-
fn named(mut self, name: &str) -> FooBuilder {
29+
pub fn name(mut self, bar: String) -> FooBuilder {
2830
// Set the name on the builder itself, and return the builder by value.
31+
self.bar = bar;
32+
self
2933
}
3034

31-
// More methods that take `mut self` and return `FooBuilder` setting up
32-
// various aspects of a Foo.
33-
...
34-
3535
// If we can get away with not consuming the Builder here, that is an
36-
// advantage. It means we can use the builder as a template for constructing
37-
// many Foos.
38-
fn finish(&self) -> Foo {
36+
// advantage. It means we can use the FooBuilder as a template for constructing many Foos.
37+
pub fn build(self) -> Foo {
3938
// Create a Foo from the FooBuilder, applying all settings in FooBuilder to Foo.
39+
Foo { bar: self.bar }
4040
}
4141
}
4242

43-
fn main() {
44-
let f = FooBuilder::new().named("Bar").with_attribute(...).finish();
43+
#[test]
44+
fn builder_test() {
45+
let foo = Foo {
46+
bar: String::from("Y"),
47+
};
48+
let foo_from_builder: Foo = FooBuilder::new().name(String::from("Y")).build();
49+
assert_eq!(foo, foo_from_builder);
4550
}
46-
4751
```
4852

4953

@@ -91,10 +95,10 @@ one can write code like
9195
let mut fb = FooBuilder::new();
9296
fb.a();
9397
fb.b();
94-
let f = fb.finish();
98+
let f = fb.build();
9599
```
96100

97-
as well as the `FooBuilder::new().a().b().finish()` style.
101+
as well as the `FooBuilder::new().a().b().build()` style.
98102

99103
## See also
100104

0 commit comments

Comments
 (0)