Rust, Software Development

How to use Strategy Design Pattern in Rust

This post is about how to use the Strategy Design Pattern in Rust.

Strategy Pattern

This Design Pattern replaces a behavior with different implementation at run-time or sometimes at load-time using configuration. Two entities could have different implementations of the same behavior. Please read the Strategy Pattern for more information.

Strategy Pattern Implementation

Our example is about ducks. A model duck, a mallard duck, and a dead duck. These are their behaviors:

  • A model duck does not fly but can quack.
  • A Mallard duck can do both.
  • A dead duck cannot do any of them!

Then, we will modify the codes later to add a RoboDuck that has the same set of behaviors but works differently.

The following struct represents a duck.

fly_behavior  and quack_behavior are traits.

Behavior Strategy and Implementations

The first is can-fly behavior. Some ducks can fly, some can’t.

Cannot-fly behavior.

Cannot-quack behavior.

Can-quack behavior.

struct Duck impl

The new function uses the Factory Design Pattern to make our codes simpler.

The impl for the Debug trait displays the duck’s name via println! and a struct instance.

Usage and Demo

These codes create three types of duck, display their names, and make them behave.

Output:

So, where is the part about replacing behavior with different implementation? It is in the new function for the Duck struct. Use Strategy Design pattern in Rust to quickly come up with any type of duck with correct set behavior without much code changes.

How do we change the codes if we include a RoboDuck? First, we make DuckTypeEnum::ROBO. Second, create structs for “robotic” behaviors and implement them.

Third, update the new function as follows. Notice we added a match rule to create a RoboDuck by specifying the new behaviors.

Finally, use the RoboDuck in main.rs.

We tested the codes using Rust 1.39.0.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like