Rust:Using the builder pattern

内容纲要

Using the builder pattern

Sometimes you need something between the customization of the constructor and the implicitness of the default implementation. Enter the builder pattern, another technique frequently used by the Rust standard library, as it allows a caller to fluidly chain together configurations that they care about and lets them ignore details that they don’t care about.

Rust 中的 build ,即是函数式编程,如何熟悉 C#,那么对 Linq 肯定不会陌生。

每个函数都要返回 “自身”(&self),当构建完毕后,使用 build() 函数返回一个数据。

假如你有一份购物清单如下:

struct shop_list {
    Apple: i32,
    pineapple: i32,
    orange: i32,
}

我们可以使用构建器来动态构建清单,定义一个构建器如下:

struct  shop_list_builder{
        list: shop_list,
}

实现构建器:

impl shop_list_builder {
    fn new() -> Self {
        shop_list_builder {
            list: shop_list {
                Apple: 0,
                pineapple: 0,
                orange: 0,
            },
        }
    }
    // build

    fn apple(mut self, number: i32) -> Self {
        self.list.Apple = number;
        self
    }

    fn pineapple(mut self, number: i32) -> Self {
        self.list.pineapple = number;
        self
    }

    fn orange(mut self, number: i32) -> Self {
        self.list.orange = number;
        self
    }

    // build has complete

    fn build(mut self) -> shop_list {
        self.list
    }
}

使用:

    let instance = shop_list_builder::new()
        .apple(12)
        .pineapple(13)
        .orange(14)
        .build();
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注