用Rust实现23种设计模式之简单工厂

在 Rust 中,可以使用结构体和 trait 来实现工厂方法模式。工厂方法模式是一种创建型设计模式,通过定义一个创建对象的接口,让子类决定实例化哪个类。下面是一个简单的示例,展示了如何使用 Rust 实现工厂方法模式:

bash 复制代码
// 定义产品 trait
trait Product {
    fn operation(&self);
}
// 实现具体产品
struct ConcreteProductA;
impl Product for ConcreteProductA {
    fn operation(&self) {
        println!("ConcreteProductA operation");
    }
}
struct ConcreteProductB;
impl Product for ConcreteProductB {
    fn operation(&self) {
        println!("ConcreteProductB operation");
    }
}
// 定义工厂 trait
trait Factory {
    fn create_product(&self) -> Box<dyn Product>;
}
// 实现具体工厂
struct ConcreteFactoryA;
impl Factory for ConcreteFactoryA {
    fn create_product(&self) -> Box<dyn Product> {
        Box::new(ConcreteProductA)
    }
}
struct ConcreteFactoryB;
impl Factory for ConcreteFactoryB {
    fn create_product(&self) -> Box<dyn Product> {
        Box::new(ConcreteProductB)
    }
}
fn main() {
    // 使用具体工厂创建具体产品
    let factory_a: Box<dyn Factory> = Box::new(ConcreteFactoryA);
    let product_a = factory_a.create_product();
    product_a.operation();
    let factory_b: Box<dyn Factory> = Box::new(ConcreteFactoryB);
    let product_b = factory_b.create_product();
    product_b.operation();
}

在上述示例中,我们首先定义了一个 Product trait,它定义了产品的操作方法。然后,我们实现了两个具体产品 ConcreteProductA 和 ConcreteProductB ,它们都实现了 Product trait。

接下来,我们定义了一个 Factory trait,它定义了创建产品的方法。然后,我们实现了两个具体工厂 ConcreteFactoryA 和 ConcreteFactoryB ,它们分别实现了 Factory trait,并分别创建了 ConcreteProductA 和 ConcreteProductB 。

在 main 函数中,我们使用具体工厂创建具体产品,并调用产品的操作方法。

这样,通过工厂方法模式,我们可以在运行时动态选择具体工厂和产品,实现了创建对象的解耦和灵活性。

相关推荐
梦醒沉醉41 分钟前
3、Rust参考手册——宏
rust
码匠许师傅12 小时前
【设计模式精讲】22.中介者模式(Mediator)
c++·设计模式·软件工程·uml·中介者模式
Amos_Web18 小时前
Rspack 源码解析(三):从入口到依赖图,读懂 Make 阶段的 Rust 任务循环
前端·rust
2401_8685347820 小时前
网规备考_2.4 路由协议
c++·设计模式
cpp_learner21 小时前
C++ 实现责任链模式(Chain of Responsibility):从一堆 if-else 到可插拔的处理管道
c++·设计模式
码匠许师傅21 小时前
【设计模式精讲】23.备忘录模式(Memento)
c++·设计模式·软件工程·uml·备忘录模式
小灰灰搞电子1 天前
Rust+Slint 实现左右伸缩式图片浏览器源码分享
rust·slint·图片伸缩浏览器
新知图书2 天前
第8章 多智能体协同
人工智能·设计模式·智能体
京师20万禁军教头2 天前
39面向对象(高级)-设计模式
java·开发语言·设计模式
传奇开心果编程2 天前
【Rust入门知识点学与练】第11课:HashMap 键值对集合
开发语言·学习·rust