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

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

相关推荐
小吕学编程24 分钟前
策略模式实战:Spring中动态选择商品处理策略的实现
java·开发语言·设计模式
pan_junbiao1 小时前
Spring框架的设计模式
java·spring·设计模式
UestcXiye1 小时前
Rust 学习笔记:关于智能指针的练习题
rust
蔡蓝14 小时前
设计模式-建造者模式
服务器·设计模式·建造者模式
维维酱16 小时前
Rust - 互斥锁
rust
维维酱16 小时前
Rust - 共享状态的并发
rust
ArcX19 小时前
从 JS 到 Rust 的旅程
前端·javascript·rust
Humbunklung19 小时前
Rust Floem UI 框架使用简介
开发语言·ui·rust
不伤欣19 小时前
游戏设计模式 - 子类沙箱
游戏·unity·设计模式
漫谈网络19 小时前
MVC与MVP设计模式对比详解
设计模式·mvc