Towards Dev

A publication for sharing projects, ideas, codes, and new theories.

Follow publication

Design Patterns in Rust: Abstract Factory, the flexible production of objects — Hacking with rust

Iede Snoek
Towards Dev
Published in
4 min readOct 8, 2023

--

Introduction

The Abstract Factory Pattern is a way to group the creation of related objects, like products of a certain brand or make by building a common factory interface. If this all sounds abstract, a picture can help:

A short breakdown:

  • All the factories have a common interface called AbstractFactory
  • The concrete factories, in our diagram there are two, implement this interface
  • These concrete factories produce objects with a common interface so those are interchangeable. In our example those are called AbstractProductOne and AbstractProductTwo

This is a somewhat more complicated design pattern, but when used well can lead to interchangeable concrete implementations. However, considering the relative complexity of this pattern, it will require extra initial work. Also, due to the high abstraction levels, it can lead in some cases to code that is more difficult to test, debug and maintain.

So, even though this pattern is very flexible and powerful, use it wisely and sparingly.

Implementation in Rust

We start by defining two interfaces: AbstractCar and AbstractBike:

trait AbstractCar { 
fn description(&self)->String;
}

trait AbstractBike {
fn description(&self)->String;
}

Both interfaces simply define a description() method which renders a string representation of either a car or a bike.

We need to be able to make these vehicles, and that is why we need a VehicleFactory interface:

trait VehicleFactory { 
fn create_car(&self,color:String)->Box<dyn AbstractCar>;
fn create_bike(&self,number_of_wheels:i8)->Box<dyn AbstractBike>;
}

Two methods, one to produce an AbstractCar, the other to produce an AbstractBike

Next we will define the concrete implementation of a car, a VolkswagenCar:

struct VolksWagenCar { 
make: String,
color: String,
}

impl VolksWagenCar {
fn new(color:String)->Self {
VolksWagenCar {…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

--

--

Published in Towards Dev

A publication for sharing projects, ideas, codes, and new theories.

Written by Iede Snoek

A love of music and of programming, that is what makes me tick, over 25 years of experience in IT, and a lifelong love of music is what makes me live.

No responses yet

Write a response