用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 函数中,我们使用具体工厂创建具体产品,并调用产品的操作方法。

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

相关推荐
SomeOtherTime5 小时前
第 11 讲(大结局):编译期元编程与零拷贝架构——卫生声明宏(macro_rules!)、过程宏 AST 手术刀与 Serde 零反射序列化的终极合龙
rust
dahaihua3336 小时前
用 SysML 表达航电系统架构(附建模示例)
设计模式·重构·系统架构·集成测试·需求分析·学习方法
SomeOtherTime10 小时前
番外篇(第 12 讲):走向工业界深水区——从物理定律看 Rust 在真实工程中的“降维打击”与“阿喀琉斯之踵”
开发语言·rust
Kapaseker11 小时前
Rust 桌面开发到底怎么选?先看这篇文章!
rust
奶油话梅糖12 小时前
容器启停 2.5 毫秒:11 天 1,700 Star 的 Kiri,用一个 900 KB 的 PID 1 干掉了 runc 和 dockerd
前端·人工智能·rust
wflynn1 天前
GitHub 今日推荐|kiri:clone3 系统调用直达容器,2.5 毫秒启动无 runc 中间层
docker·rust·kubernetes·开源·github·containers
SomeOtherTime1 天前
第 4 讲:突破静态枷锁——智能指针(Box/Rc/Arc)与内部可变性(Cell/RefCell/UnsafeCell)的内存暗道
rust
wy_hhxx1 天前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent
AAA修煤气灶刘哥1 天前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
SomeOtherTime1 天前
第 9 讲:异步并发与 Pin 的底层解剖——async/await 无栈协程状态机脱糖、自引用死锁的终极救赎与 Future/Waker 驱动模型
rust