【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);
}
相关推荐
座山雕~1 天前
Springboot
android·spring boot·后端
韩立学长1 天前
基于Springboot流浪动物救助系统o8g44kwc(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
我命由我123451 天前
充血模型与贫血模型
java·服务器·后端·学习·架构·java-ee·系统架构
分布式存储与RustFS1 天前
RustFS在AI场景下的实测:从GPU到存储的完整加速方案
开发语言·人工智能·rust·对象存储·企业存储·rustfs·minio国产化替代
小镇学者1 天前
【other】Goofy Node
后端
颜淡慕潇1 天前
动态代理赋能:高效爬取沃尔玛海量商品信息与AI分析实战
人工智能·后端
Geoking.1 天前
【设计模式】中介者模式(Mediator)详解
java·设计模式·中介者模式
半夏知半秋1 天前
kcp学习-通用的kcp lua绑定
服务器·开发语言·笔记·后端·学习
hero.fei1 天前
kaptcha 验证码生成工具在springboot中集成
java·spring boot·后端
w***76551 天前
存储技术全景:从基础原理到未来趋势
spring boot·后端·mybatis