Rust设计模式之建造者模式
什么是建造者模式
即将结构体属性方法与构建解离,使用专门的builder进行建造,说白了就是new和其他的方法分开,集中处理更方便。
直接上代码:
rust
#[derive(Debug)]
struct children {
name: String,
age: u32,
}
impl children {
pub fn find_generator() -> Generator {
Generator::default()
}
}
#[derive(Default)]
struct Generator {
name: String,
age: u32,
//... and so on...
}
impl Generator {
pub fn new() -> Generator {
Generator {
name: String::from("generator"),
age: 11,
//... and so on...
}
}
pub fn buildchildren(self) -> children {
children {
name: self.name,
age: self.age,
//... and so on...
}
}
}
fn main() {
let child_from_generator = Generator::new().buildchildren();
println!("{:?}", child_from_generator);
}