Member-only story
Design Patterns in Rust: Abstract Factory, the flexible production of objects — Hacking with rust
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 {…