0

How to use Command Design Pattern in Rust

Last Updated on

This post is about the Command Design Pattern in Rust.

Command Design Pattern

This Design Pattern uses commands to wrap and invoke capabilities. A car can run faster and slower. We can have commands AccelerateCommand and DecelerateCommand for increasing and decreasing speed, respectively. We can also have AccelerateAndDecelerateCommand to run both capabilities in a particular order. Please read Command Pattern for more details.

Design Pattern Implementation

Our example is about cars and what they can do. A car can Startup and Shutdown. It can also increase or decrease its speed. Moreover, it can Turn Left and Turn Right. We can represent cars in Rust as follow.

Structs and Command Trait in Rust

We will have a struct that implements the Command trait for each function in the Car struct.

Startup Command

This capability enables a car to start up its engine.

Shutdown Command

Shutdown enables a car to turn its engine off.

Accelerate Command

When a car goes faster, it accelerates.

Decelerate Command

When a car goes slower, it decelerates.

Turn Left Command

This capability allows the driver to change direction.

Turn Right Command

This capability allows the driver to change direction.

Reverse Command

The CarReverseCommand struct allows a car to run in reverse, which is typically is for parking.

Stop Command

Lastly, this capability allows a car to stop.

Command Pattern Usage

Now consider we are going somewhere. We could use the car in some arranged ways to reach a destination. First, we start it up. Then, the increase in speed. Then, the decrease in speed before making turns, etc.

Output:

Tested with Rust 1.39.0.

That’s it! That’s how to use Command Design Pattern in Rust. The beauty of this pattern is it allows for uniformity by using a common Command trait. We could be more specific with our codes and come up with different types of cars. We could have more commands but still, have the same core codes to process them.

Karl San Gabriel

Karl San Gabriel

Professional Software Developer