Skip to main content

Command Palette

Search for a command to run...

Factory Design Pattern in Rust - my exploration continues...

Updated
1 min readView as Markdown
S
In search of WhoAmI...

Living a purposeful life - Karmyog... Salvation... Awakening...

You know, the best way to learn a modern computer programming language is to apply the nuances in designing a real life problem. This way I learned C++, Java and Python. And now I am applying the same logic while picking up Rust.

in Rust I keep my trust...

So...

here we go...

A simple factory design pattern in Rust - my second program of Rust.

Enjoy...

Source Code:

trait Food {
    fn display(&self);
}

enum FoodType {
    Chocolate,
    Biscuit,
}

struct Chocolate {}

impl Food for Chocolate {
    fn display(&self) {
        println!("A chocolate is made...");
    }
}

struct Biscuit {}

impl Food for Biscuit {
    fn display(&self) {
        println!("A biscuit is made...");
    }
}

struct FoodFactory;

impl FoodFactory {
    fn new_food(item: &FoodType) -> Box<dyn Food> {
        match item {
            FoodType::Chocolate => Box::new(Chocolate {}),
            FoodType::Biscuit => Box::new(Biscuit {}),
        }
    }
}

fn main() {
    let food = FoodFactory::new_food(&FoodType::Chocolate);
    food.display();
    let food = FoodFactory::new_food(&FoodType::Biscuit);
    food.display();
}

More from this blog

Som's Tech World...

150 posts

I am in search of WhoAmI. This is my own world of technologies and software. I believe in the following simple fact of life... To win is no more than this... To rise each time you fall...