用Rust实现23种设计模式之适配器

关注我,学习Rust不迷路

在 Rust 中,可以使用结构体和 trait 来实现适配器模式。适配器模式是一种结构型设计模式,它允许将一个类的接口转换为客户端所期望的另一个接口。下面是一个使用 Rust 实现适配器模式的示例,带有详细的注释和说明:

bash 复制代码
// 定义目标接口
trait Target {
    fn request(&self);
}
 // 定义适配者接口
trait Adaptee {
    fn specific_request(&self);
}
 // 实现适配者接口
struct ConcreteAdaptee;
 impl Adaptee for ConcreteAdaptee {
    fn specific_request(&self) {
        println!("Specific request from Adaptee");
    }
}
 // 实现适配器
struct Adapter {
    adaptee: Box<dyn Adaptee>,
}
 impl Adapter {
    fn new(adaptee: Box<dyn Adaptee>) -> Self {
        Adapter { adaptee }
    }
}
 impl Target for Adapter {
    fn request(&self) {
        self.adaptee.specific_request();
    }
}
 fn main() {
    // 创建适配者对象
    let adaptee: Box<dyn Adaptee> = Box::new(ConcreteAdaptee);
     // 创建适配器对象
    let adapter = Adapter::new(adaptee);
     // 调用目标接口
    adapter.request();
}

在上述示例中,我们首先定义了目标接口 Target 和适配者接口 Adaptee 。然后,我们实现了适配者接口 Adaptee 的具体类型 ConcreteAdaptee ,并在其中实现了 specific_request 方法。

接下来,我们定义了适配器 Adapter ,它包含一个适配者对象。适配器实现了目标接口 Target ,并在 request 方法中调用适配者的 specific_request 方法。

main 函数中,我们创建了一个适配者对象 adaptee ,并将其传递给适配器的构造函数创建适配器对象 adapter 。然后,我们通过调用目标接口的 request 方法,实际上调用了适配者的 specific_request 方法。

通过适配器模式,我们可以将一个类的接口转换为另一个类的接口,以满足客户端的需求。适配器模式可以帮助我们在不修改现有代码的情况下重用已有的类,提高代码的可维护性和扩展性。

关注我,学习Rust不迷路

相关推荐
咖啡八杯11 小时前
GoF设计模式——策略模式
java·后端·spring·设计模式
doiito19 小时前
【Agent Harness】Gliding Horse 本体论系统设计:给 AI Agent 装上“语义大脑”
ai·rust·架构设计·系统设计·ai agent
大卫小东(Sheldon)2 天前
Rust 推荐使用宏而非普通函数的场景
rust
doiito2 天前
【Agent Harness】为什么我把 JSON‑LD “编译成 DAG” 后,整个 Agent 平台立刻聪明了
ai·rust·架构设计·系统设计·ai agent
jump_jump2 天前
为了重玩金庸群侠传,我研究了一下 Ruffle 怎么复活 Flash
游戏·rust·github
槑有老呆2 天前
别再手搓 Prompt 了,那个叫"手动挡循环"
设计模式
用户6919026813393 天前
Vibe Coding 开发项目的基本范式
人工智能·设计模式·代码规范
星栈3 天前
Dioxus 多页面怎么做:`dioxus-router`、嵌套路由、`Outlet` 和页面组织,一篇给你讲顺
前端·rust·前端框架
怕浪猫4 天前
领域特定语言(Domain-Specific Language, DSL)
设计模式·程序员·架构
Rust研习社5 天前
组合真的优于继承吗?为什么 Rust 和 Go 都拥抱组合舍弃继承?
后端·rust·编程语言