【Rust实现命令模式】

Rust实现命令模式


什么是命令模式

命令模式,即通过统一接口,如C#interface,亦或C++中的抽象类的=0方法,通过定义统一的接口,在定义不同的对象,为之接口实现具体的方法逻辑,再通过统一的管理类,将其存储在容器中如List或Deque等,在真正执行的时候按照顺序依次执行接口定义的方法就像执行命令一样。

命令模式的应用场景

  1. 常见的 Server数据库执行操作。
  2. Tracing 错误跟踪
  3. Server端在处理请求时。
  4. and so on

命令模式的在Rust中的关系图

Rust中的命令模式代码示例

rust 复制代码
trait Execute {
    fn execute(&self) -> String;
}

struct Login {
    username: String,
    password: String,
}

impl Execute for Login {
    fn execute(&self) -> String {
        // Simulate login logic
        if self.username == "admin" && self.password == "secret" {
            format!("login admin logged in")
        } else {
            format!("login customer logged in")
        }
    }
}

struct Logout {
    username: String,
}

impl Execute for Logout {
    fn execute(&self) -> String {
        // Simulate logout logic
        format!("{} Logout!", self.username)
    }
}

struct Server {
    requests: Vec<Box<dyn Execute>>,
}

impl Server {
    fn new() -> Self {
        Self { requests: vec![] }
    }

    fn add_request(&mut self, request: Box<dyn Execute>) {
        self.requests.push(request);
    }

    fn handlers(&self) -> Vec<String> {
        self.requests.iter().map(|req| req.execute()).collect()
    }
}

fn main() {
    let mut server = Server::new();
    server.add_request(Box::new(Login {
        username: "admin".to_string(),
        password: "secret".to_string(),
    }));
    server.add_request(Box::new(Login {
        username: "bob".to_string(),
        password: "bob".to_string(),
    }));
    server.add_request(Box::new(Login {
        username: "men".to_string(),
        password: "men".to_string(),
    }));
    server.add_request(Box::new(Logout {
        username: "men".to_string(),
    }));
    server.add_request(Box::new(Logout {
        username: "bob".to_string(),
    }));

    let handlers = server.handlers();
    for handler in handlers {
        println!("{}", handler);
    }
}

运行结果

rust 复制代码
login admin logged in
login customer logged in
login customer logged in
men Logout!
bob Logout!

总结

命令模式较为常用,尤其实在后端开发中,了解掌握命令模式对服务器框架源码理解也有好处,模式不是必选项,而是锦上添花。

"我们从来都不清楚选择正确与否,只是努力的将选择变得正确."

相关推荐
阿星AI工作室4 小时前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
Ranger09295 小时前
鸿蒙开发新范式:Gpui
rust·harmonyos
_哆啦A梦1 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
DongLi013 天前
rustlings 学习笔记 -- exercises/05_vecs
rust
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054964 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django