建造者

说明

通过调用建造者来构造对象。

示例

  1. #[derive(Debug, PartialEq)]
  2. pub struct Foo {
  3. // Lots of complicated fields.
  4. bar: String,
  5. }
  6. impl Foo {
  7. // This method will help users to discover the builder
  8. pub fn builder() -> FooBuilder {
  9. FooBuilder::default()
  10. }
  11. }
  12. #[derive(Default)]
  13. pub struct FooBuilder {
  14. // Probably lots of optional fields.
  15. bar: String,
  16. }
  17. impl FooBuilder {
  18. pub fn new(/* ... */) -> FooBuilder {
  19. // Set the minimally required fields of Foo.
  20. FooBuilder {
  21. bar: String::from("X"),
  22. }
  23. }
  24. pub fn name(mut self, bar: String) -> FooBuilder {
  25. // Set the name on the builder itself, and return the builder by value.
  26. self.bar = bar;
  27. self
  28. }
  29. // If we can get away with not consuming the Builder here, that is an
  30. // advantage. It means we can use the FooBuilder as a template for constructing
  31. // many Foos.
  32. pub fn build(self) -> Foo {
  33. // Create a Foo from the FooBuilder, applying all settings in FooBuilder
  34. // to Foo.
  35. Foo { bar: self.bar }
  36. }
  37. }
  38. #[test]
  39. fn builder_test() {
  40. let foo = Foo {
  41. bar: String::from("Y"),
  42. };
  43. let foo_from_builder: Foo = FooBuilder::new().name(String::from("Y")).build();
  44. assert_eq!(foo, foo_from_builder);
  45. }

出发点

当你需要很多不同的构造器或者构造器有副作用的时候这个模式会有帮助。

优点

将构造方法与其他方法分开。

防止构造器数量过多。

即使构造器本身很复杂,也可以做到封装后一行初始化。

缺点

与直接构造一个结构体或者一个简单的构造函数相比,这种方法太复杂。

讨论

因为Rust缺少重载功能,所以这种模式在Rust里比其他语言更常见。由于一个方法一个名称不能重载,所以Rust相比于C++、Java来说更不适合写很多构造器。

这种模式经常不是为了作为构造器而设计。例如std::process::CommandChild的构造器(一个进程)。这种情况下没有使用TTBuilder命名模式。

下面的例子按值获取和返回。然而更符合人体工程学(以及更效率)的方法是按可变引用获取和返回。借用检查器将会帮助我们。传入传出可变引用将会让我们从下面这种代码:

  1. let mut fb = FooBuilder::new();
  2. fb.a();
  3. fb.b();
  4. let f = fb.build();

转变为FooBuilder::new().a().b().build() 风格代码。

参阅