In this lesson, you will learn how to route system requests through a configurable pipeline of specialized, trait-compliant workers to process data in discrete, manageable steps.
Understanding the Chain of Command
While the Chain of Responsibility (which we covered earlier) allows a request to pass through a series of handlers until one finally processes it, the Chain of Command is about collective transformation. In this architecture, every request passes through every stage in a pre-configured pipeline, where each stage performs a specific operation or validation.
Think of it like an assembly line: each worker (a "Command") takes an input, modifies it, or validates it, and passes it to the next worker in line.
Defining the Pipeline
To implement this in Rust, we define a common trait that every worker in our pipeline must implement. This ensures that our controller doesn't need to know the specific logic of each step, only that it is a valid Command.
trait Command {
fn execute(&self, data: &mut String) -> Result<(), String>;
}
struct Pipeline {
workers: Vec<Box<dyn Command>>,
}
impl Pipeline {
fn run(&self, mut data: String) -> Result<String, String> {
for worker in &self.workers {
worker.execute(&mut data)?;
}
Ok(data)
}
}
Why Use This Pattern?
By using this architecture, you gain two massive advantages:
- Configurability: You can inject different sequences of commands at runtime without changing the core system logic.
- Separation of Concerns: Each
Commandstruct is responsible for exactly one task (e.g., sanitizing input, checking permissions, or formatting output), making your code significantly easier to test and debug.
Because we rely on trait objects (Box<dyn Command>), we can store a heterogeneous collection of commands in a single vector. When the Pipeline processes a request, it iterates through the list, effectively "piping" the request through each worker. If any command fails, the entire chain halts, ensuring your system maintains a strict, safe state at every transition.
Key Takeaway: The Chain of Command architecture modularizes complex processes by routing requests through a sequential, configurable pipeline of trait-compliant workers.