设计模式的使用,是对开发者的考验。比如说在 Golang 中最常用的是工厂模式,创建模块时,以 Struct 为基础,常命名为 NewXX 开头发的方法作为工厂模式。而在 Rust 中,常用的则是建造模式(builder),由此来创建某一模块或功能的集合。
另外在 Rust 中独有的模式,例如 Drop
Builder Builder1 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.
建造者是一个创造性的设计模式,让你一步步构建复杂的对象。模式允许你使用相同的结构代码构建不同的类型和表现对象。
例子使用Box Builder,构建不同尺寸的盒子,通过链式调用设置不同的盒子属性
struct Box { width: u32, height: u32, } struct BoxBuilder { width: Option<u32>, height: Option<u32>, } impl BoxBuilder { fn new() -> Self { BoxBuilder { width: None, height: None, } } fn default() -> Self { BoxBuilder { width: Some(30), height: Some(30), } } fn set_width(mut self, width: u32) -> Self { self.width = Some(width); self } fn set_height(mut self, height: u32) -> Self { self.height = Some(height); self } fn build(self) -> Box { let width = self.width.unwrap(); let height = self.height.unwrap(); Box { width, height } } } fn main() { let box1: Box = BoxBuilder::new().set_height(20).set_width(10).build(); println!( "the box1 width is {}, height is {}.", box1.width, box1.height ); let box2: Box = BoxBuilder::default().build(); println!( "the box2 width is {}, height is {}.", box2.width, box2.height ); } output:
...