Design Pattern, Rust, Software Development

The Composite Design Pattern In Rust

This post shows how to use the Composite design pattern in Rust. Also, it offers a sample implementation with two levels of composition. For instance, we have a group of lists of products.

The Composite Design Pattern Use Case

Our use case is relatively simple for this post – displaying a product’s information. Moreover, the data may come from a single product, a collection of products, or a group of collections. Applying the Composite design pattern, we have the Sellable trait that the relevant structs need to implement.

A Rust Trait To Process Structs Uniformly

The Sellable trait allows us to process any structs that implement the trait uniformly. For instance, consider the following Rust trait. It has five methods relevant to a single product and a collection of products. Therefore, it will help us implement the Composite design pattern in Rust.

Next, we have a processor of Sellable struct instances. Consider the following struct and its implementation.

The SellableProcessor displays a summary and details of the product or products if we are dealing with collections.

Rust Struts That Implement The Composite Pattern

Then, we go through the Rust structs that implement the Composite design pattern. First, we have the Product struct that has a straightforward implementation. Moreover, it does not allow for multiple products because it is our base struct to build on.  Hence, the panic macro in the add method.

It also returns an empty list of Sellables via the get_information method because we have the get_name and get_price  methods to provide data. Meanwhile, the get_count returns 1 to represent a single product.

Next, we have another struct that holds a collection of Sellable products for our Composite design pattern implementation. Unlike the base struct, the CollectionOfProducts struct does more computation on the list of items. For example, the price is the sum of all prices, and the product count is the size of the collection.

Lastly, we have a struct that represents a group of collections of products. More importantly, it pushes our Composite design pattern in Rust to the limit by handling multilevel composition.

The Composite Design Pattern Demo

We need a main function with sample data to test our Composite design pattern Rust codes. For example, consider the following codes. They have test cases for a single product, a collection of products, and a group of collections of products.

When we run all the codes, we get the following sample result.

We tested the codes using Rust 1.60.0.


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