【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!

总结

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

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

相关推荐
liu_yueyang几秒前
JavaScript VMP (Virtual Machine Protection) 分析与调试
开发语言·javascript·ecmascript
前端 贾公子2 分钟前
tailwindCSS === 使用插件自动类名排序
java·开发语言
10岁的博客3 分钟前
代码编程:一场思维与创造力的革命
开发语言·算法
七七七七073 分钟前
C++类对象多态基础语法【超详细】
开发语言·c++
C嘎嘎嵌入式开发29 分钟前
python之set详谈
开发语言·python
定偶29 分钟前
进制转换小题
c语言·开发语言·数据结构·算法
花好月圆春祺夏安1 小时前
基于odoo17的设计模式详解---备忘模式
数据库·设计模式
小庞在加油1 小时前
Apollo源码架构解析---附C++代码设计示例
开发语言·c++·架构·自动驾驶·apollo
专注VB编程开发20年2 小时前
各版本操作系统对.NET支持情况(250707更新)
开发语言·前端·ide·vscode·.net
我喜欢就喜欢2 小时前
RapidFuzz-CPP:高效字符串相似度计算的C++利器
开发语言·c++