Builder^1 is a creational design pattern that lets you construct complex objects step by step. The pattern allows you to produce different types and representations of an object using the same construction code.
fnmain() { letbox1: Box = BoxBuilder::new().set_height(20).set_width(10).build(); println!( "the box1 width is {}, height is {}.", box1.width, box1.height );
letbox2: Box = BoxBuilder::default().build(); println!( "the box2 width is {}, height is {}.", box2.width, box2.height ); }
output:
1 2 3 4 5 6
➜ design git:(master) ✗ cargo run Compiling design v0.1.0 (/Users/yother/WorkSpace/BackEnd/Rust/module/design) Finished dev [unoptimized + debuginfo] target(s) in 1.06s Running `target/debug/design` the box1 width is 10, height is 20. the box2 width is 30, height is 30.
fnmain() { letmut builder = BoxBuilder::default(); letsmall_box = Box::small_box(&mut builder); println!( "build small box, the spec is: width({}), height({})", small_box.width, small_box.height );
letmid_box: Box = Box::mid_box(&mut builder); println!( "build mid box, the spec is: width({}), height({})", mid_box.width, mid_box.height );
letbig_box: Box = Box::big_box(&mut builder); println!( "build big box, the spec is: width({}), height({})", big_box.width, big_box.height ); }
output:
1 2 3 4 5 6 7
➜ design git:(master) ✗ cargo run Compiling design v0.1.0 (/Users/yother/WorkSpace/BackEnd/Rust/module/design) Finished dev [unoptimized + debuginfo] target(s) in 0.22s Running `target/debug/design` build small box, the spec is: width(10), height(10) build mid box, the spec is: width(20), height(20) build big box, the spec is: width(30), height(30)
which lets you customize what happens when a value is about to go out of scope. You can provide an implementation for the Drop trait on any type, and that code can be used to release resources like files or network connections.