Revolution in the Toy Factory: Dancing with Rust through the Factory Method Pattern

[tr] Türkçe Oku

2024-04-17

Problem:

Once upon a time, there was a large toy factory that produced various types of toys. The factory manager wanted to make the production process of different types of toys more efficient. Setting up separate production lines for each type of toy was both costly and time-consuming. The manager aimed to increase the factory’s capacity and produce innovative toys by standardizing production processes and entering new markets.

Solution:

The manager decided to solve this problem by creating a general production interface instead of separate production lines for each type of toy. This interface provided a flexible structure to manage the fabrication processes of different types of toys. An R&D department was established, and product development activities for new categories such as electronic toys and plush toys were initiated.

Electronic toys captured children’s interest with their interactive features, while plush toys became the best friends of young children with their soft structures and cute appearances. To support this new product diversity, the manager set up both an Electronic Toy Factory and a Plush Toy Factory. Thus, the factory was able to produce new products more quickly and flexibly than the old production lines.

Result:

These innovations distinguished the factory from other toy manufacturers in the market, leading to great success. The manager successfully restructured the production process and contributed significantly to the growth of the factory by responding to market demands both domestically and internationally. The factory became a recognized brand both in the domestic and international markets.

Factory Method Pattern: From Story to Design

The strategy that was key to the factory manager’s success in the story above is actually an application of the Factory Method Pattern. This pattern is ideal for simplifying production processes, reducing costs, and improving response time.

Structure and UML Class Diagram of the Factory Method Pattern

Factory Method Pattern relies on delegating object creation processes to an interface and then to subclasses that implement this interface. This design facilitates changes when new product types are added and greatly enhances the system’s expansibility. Especially in our factory story, the manager’s decision to set up a separate factory for each type of toy is a concrete example of this pattern.

Core Components

  1. Product (Product):

    • The Toy trait defines the produce method that all toys must have, serving as a common interface.
  2. Concrete Product (Concrete Product):

    • Classes such as WoodenToy, PlasticToy, ElectronicToy, and PlushToy embody this interface.
  3. Creator (Creator):

    • The ToyFactory trait defines the factory method (create_toy) that will create a product instance.
  4. Concrete Creator (Concrete Creator):

    • Classes such as WoodenToyFactory, PlasticToyFactory, ElectronicToyFactory, and PlushToyFactory return the respective product instance.

UML Class Diagram

+------------------+          +--------------------+
| <<interface>>    |          | <<interface>>      |
| Toy              |<---------| ToyFactory         |
+------------------+          +--------------------+
| + produce(): String |       | + create_toy(): Toy|
+------------------+          +--------------------+
          ^                                ^
          |                                |
+---------+-------+             +----------+----------+
| WoodenToy       |             | WoodenToyFactory    |
+-----------------+             +---------------------+
| + produce(): String |         | + create_toy(): Toy |
+-----------------+             +---------------------+
          ^                                ^
          |                                |
+---------+-------+             +----------+----------+
| PlasticToy      |             | PlasticToyFactory   |
+-----------------+             +---------------------+
| + produce(): String |         | + create_toy(): Toy |
+-----------------+             +---------------------+
          ^                                ^
          |                                |
+---------+-------+             +----------+----------+
| ElectronicToy   |             | ElectronicToyFactory|
+-----------------+             +---------------------+
| + produce(): String |         | + create_toy(): Toy |
+-----------------+             +---------------------+
          ^                                ^
          |                                |
+---------+-------+             +----------+----------+
| PlushToy        |             | PlushToyFactory     |
+-----------------+             +---------------------+
| + produce(): String |         | + create_toy(): Toy |
+-----------------+             +---------------------+

The Factory Method Pattern is an effective way to expand and modify a product family, especially when diversity and flexibility are important. The factory manager’s success is due to the strategic and effective use of this pattern.

Implementation of the Factory Method Pattern in Rust

One of the strategies that contributed to the factory manager’s success was the Factory Method Pattern, which can be effectively implemented in the Rust programming language. Rust’s strong type system and traits provide extra security and modularity when implementing this pattern. Here is a simple implementation of the Factory Method Pattern in Rust

:

Rust Code Example:

// Toy trait definition, providing a common interface for all types of toys.
trait Toy {
    fn produce(&self) -> String;
}

// Concrete Products
struct WoodenToy;
impl Toy for WoodenToy {
    fn produce(&self) -> String {
        "A wooden toy has been produced.".to_string()
    }
}

struct PlasticToy;
impl Toy for PlasticToy {
    fn produce(&self) -> String {
        "A plastic toy has been produced.".to_string()
    }
}

struct ElectronicToy;
impl Toy for ElectronicToy {
    fn produce(&self) -> String {
        "An electronic toy has been produced. Equipped with interactive features.".to_string()
    }
}

struct PlushToy;
impl Toy for PlushToy {
    fn produce(&self) -> String {
        "A plush toy has been produced. Soft and cuddly!".to_string()
    }
}

// ToyFactory trait definition, defining the factory method for producing toys.
trait ToyFactory {
    fn create_toy(&self) -> Box<dyn Toy>;
}

// Concrete Creators
struct WoodenToyFactory;
impl ToyFactory for WoodenToyFactory {
    fn create_toy(&self) -> Box<dyn Toy> {
        Box::new(WoodenToy)
    }
}

struct PlasticToyFactory;
impl ToyFactory for PlasticToyFactory {
    fn create_toy(&self) -> Box<dyn Toy> {
        Box::new(PlasticToy)
    }
}

struct ElectronicToyFactory;
impl ToyFactory for ElectronicToyFactory {
    fn create_toy(&self) -> Box<dyn Toy> {
        Box::new(ElectronicToy)
    }
}

struct PlushToyFactory;
impl ToyFactory for PlushToyFactory {
    fn create_toy(&self) -> Box<dyn Toy> {
        Box::new(PlushToy)
    }
}

// Function to produce and test products
fn produce_toy(factory: &dyn ToyFactory) {
    let toy = factory.create_toy();
    println!("{}", toy.produce());
}

fn main() {
    let wooden_factory = WoodenToyFactory;
    let plastic_factory = PlasticToyFactory;
    let electronic_factory = ElectronicToyFactory;
    let plush_factory = PlushToyFactory;

    produce_toy(&wooden_factory);
    produce_toy(&plastic_factory);
    produce_toy(&electronic_factory);
    produce_toy(&plush_factory);
}

This Rust code represents each step of the toy production process with classes and traits. Each ToyFactory implementation uses the create_toy method to produce a specific type of toy. This way, the factory manager increases product diversity and flexibility, making the factory more efficient and innovative. Rust’s type safety and memory management features help create a less error-prone and high-performance system while implementing such a design.