July 12, 2021

composite_pattern_in_Rust

The composite Pattern is dedicated to creating a group of similar objects in a tree. This Pattern is represented as a tree, where branches are connected to others and finishes with a single leaf.

Remember: I will feature here an example of Composite Pattern, among others. The pattern form depends on the problem to resolve!

A diagram example. Interactions

The composite Pattern contains an interface with a series of Leaf and Branches.

IComponent is my trait linking the two distrinc objects: Leaf and Branch.

Class_Diagram_Composite

An example of problem resolved by the “Composite Pattern” in Rust

A classic “composite” problem is the file system from our computers!

Indeed, a folder can contain another folder. However, a file cannot hold a folder. If I generalize this with the composite Pattern format:

  • A “Folder” is a branch: It can contain another Interface “Component”.
  • A “File” is a leaf: It is a container that cannot contain another Interface “Component”.
Composite_tree

This is where the composite Pattern helps us. It creates a hierarchy composed of folders and files represented as a tree structure. By dealing with the organization with a contract (The trait), we can complete this complex structure with a scalable code. Here, the client can ignore the differences of the “tree components”.

An example of “Composite Pattern” reproduced in Rust.

The following example is an implementation of the “Composite Pattern” for the File/Folder problem.


In this code example, I recreated the following data structure in my function “create_structure()”:

Composite_Example_Rust

As you see, the standard interface is a “trait” implemented in my “structs” File and Folder.
The “Trait” is my “Contract” usable by the client to print my “Folders” and “Files” content. Then, a simple call to “open_and_print_all()” reaches my tree recursively to publish the texts.

Here, the Pattern was exploitable by Rust because it exploits an “Interface” (represented by the “trait” Component) and not the inheritance features.

Photo by Viktor Talashuk on Unsplash

About the author 

Axel Fortun

​Developer specialized in Linux environment and embedded systems.
​Knowledge in multiple languages as C/C++, Java, Python​ and AngularJs.
​Working as Software developer since 2014 with a beginning in the car industry​ and then in ​medical systems.