【Rust设计模式之建造者模式】

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);
}
相关推荐
Source.Liu3 小时前
【typenum】 8 常量文件(consts.rs)
rust
xiaolin03335 小时前
【设计模式】- 行为型模式1
设计模式·状态模式·责任链模式·策略模式·命令模式·模板方法模式·行为型模式
程序员爱钓鱼5 小时前
匿名函数与闭包(Anonymous Functions and Closures)-《Go语言实战指南》原创
后端·golang
沐土Arvin6 小时前
深入理解 requestIdleCallback:浏览器空闲时段的性能优化利器
开发语言·前端·javascript·设计模式·html
bao_lanlan7 小时前
兰亭妙微:用系统化思维重构智能座舱 UI 体验
ui·设计模式·信息可视化·人机交互·交互·ux·外观模式
言之。7 小时前
Go 语言中接口类型转换为具体类型
开发语言·后端·golang
diving deep8 小时前
XML简要介绍
xml·java·后端
总是难免8 小时前
设计模式 - 单例模式 - Tips
java·单例模式·设计模式
编程乐学(Arfan开发工程师)9 小时前
06、基础入门-SpringBoot-依赖管理特性
android·spring boot·后端
编程乐学(Arfan开发工程师)9 小时前
05、基础入门-SpringBoot-HelloWorld
java·spring boot·后端