What is a Factory Method in Rust?

In Rust, the Factory Method is a design pattern that allows you to create objects without specifying the exact class of object that will be created. It defines an interface (or a trait in Rust) for creating objects, but the specific implementation of the object creation is left to the subclasses. This pattern promotes loose coupling between the client code and the concrete classes, making the code more maintainable and extensible.

Here’s a basic code example of the Factory Method pattern in Rust:

// Define a trait for the product (objects to be created)
trait Product {
    fn display(&self);
}

// Define concrete implementations of the Product trait
struct ConcreteProductA;
impl Product for ConcreteProductA {
    fn display(&self) {
        println!("This is ConcreteProductA.");
    }
}

struct ConcreteProductB;
impl Product for ConcreteProductB {
    fn display(&self) {
        println!("This is ConcreteProductB.");
    }
}

// Define the Factory trait for creating products
trait Factory {
    fn create_product(&self) -> std::boxed::Box<dyn Product>;
}

// Define concrete implementations of the Factory trait
struct ConcreteFactoryA;
impl Factory for ConcreteFactoryA {
    fn create_product(&self) -> std::boxed::Box<dyn Product> {
        std::boxed::Box::new(ConcreteProductA)
    }
}

struct ConcreteFactoryB;
impl Factory for ConcreteFactoryB {
    fn create_product(&self) -> std::boxed::Box<dyn Product> {
        std::boxed::Box::new(ConcreteProductB)
    }
}

fn main() {
    // Client code using Factory Method
    let factory_a = ConcreteFactoryA;
    let product_a = factory_a.create_product();
    product_a.display();

    let factory_b = ConcreteFactoryB;
    let product_b = factory_b.create_product();
    product_b.display();
}

In this example:

  1. We define a Product trait that represents the objects to be created. It includes a display method that concrete products must implement.
  2. We create two concrete implementations of the Product trait: ConcreteProductA and ConcreteProductB.
  3. We define a Factory trait that includes a create_product method for creating products. The method returns a Box<dyn Product> to provide flexibility in returning different types of products.
  4. We create two concrete factories: ConcreteFactoryA and ConcreteFactoryB. Each factory implements the create_product method to create a specific type of product.
  5. In the main function, we demonstrate how to use the Factory Method pattern. We create instances of ConcreteFactoryA and ConcreteFactoryB, and then use them to create products. The client code remains unaware of the specific product implementations.

This code follows the Factory Method pattern, allowing you to create products without tightly coupling the client code to the concrete product classes or factories.

Try it out in the Rust Playground

Rust Programming

Previous article

State Pattern in Rust