Skip to content
เข้าสู่ระบบ

Builder Pattern

Builder pattern สำหรับสร้าง complex objects

#[derive(Debug)]
struct Server {
host: String,
port: u16,
max_connections: u32,
timeout: u64,
tls: bool,
}
#[derive(Default)]
struct ServerBuilder {
host: Option<String>,
port: Option<u16>,
max_connections: Option<u32>,
timeout: Option<u64>,
tls: Option<bool>,
}
impl ServerBuilder {
fn new() -> Self {
Self::default()
}
fn host(mut self, host: &str) -> Self {
self.host = Some(host.to_string());
self
}
fn port(mut self, port: u16) -> Self {
self.port = Some(port);
self
}
fn max_connections(mut self, max: u32) -> Self {
self.max_connections = Some(max);
self
}
fn timeout(mut self, seconds: u64) -> Self {
self.timeout = Some(seconds);
self
}
fn tls(mut self, enabled: bool) -> Self {
self.tls = Some(enabled);
self
}
fn build(self) -> Result<Server, &'static str> {
Ok(Server {
host: self.host.ok_or("host is required")?,
port: self.port.unwrap_or(8080),
max_connections: self.max_connections.unwrap_or(100),
timeout: self.timeout.unwrap_or(30),
tls: self.tls.unwrap_or(false),
})
}
}
fn main() {
let server = ServerBuilder::new()
.host("localhost")
.port(3000)
.max_connections(500)
.tls(true)
.build()
.unwrap();
println!("{:#?}", server);
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด