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

总结

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

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

相关推荐
晨米酱10 小时前
JavaScript 中"对象即函数"设计模式
前端·设计模式
数据智能老司机15 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机16 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机16 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机16 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
使一颗心免于哀伤17 小时前
《设计模式之禅》笔记摘录 - 21.状态模式
笔记·设计模式
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机2 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
烛阴2 天前
【TS 设计模式完全指南】懒加载、缓存与权限控制:代理模式在 TypeScript 中的三大妙用
javascript·设计模式·typescript
李广坤2 天前
工厂模式
设计模式