Builder — construct complex objects step by step.
Implementation:
1struct Server {2 host: String,3 port: u16,4 max_connections: usize,5}67struct ServerBuilder {8 host: String,9 port: u16,10 max_connections: usize,11}1213impl ServerBuilder {14 fn new() -> Self {15 Self {16 host: "localhost".into(),17 port: 8080,18 max_connections: 100,19 }20 }2122 fn host(mut self, host: &str) -> Self {23 self.host = host.into();24 self25 }2627 fn port(mut self, port: u16) -> Self {28 self.port = port;29 self30 }3132 fn build(self) -> Server {33 Server {34 host: self.host,35 port: self.port,36 max_connections: self.max_connections,37 }38 }39}4041let server = ServerBuilder::new()42 .host("0.0.0.0")43 .port(3000)44 .build();
Key: Builder for complex construction.