patterns icon indicating copy to clipboard operation
patterns copied to clipboard

Factory Method

Open simonsan opened this issue 4 years ago • 2 comments

Tracking issue for merging: https://github.com/lpxxn/rust-design-pattern/blob/master/creational/factory.rs

Example:

//! Factory method creational design pattern allows creating objects without having to specify the exact type of the object that will be created.

trait Shape {
    fn draw(&self);
}

enum ShapeType {
    Rectangle,
    Circle,
}

struct Rectangle {}

impl Shape for Rectangle {
    fn draw(&self) {
        println!("draw a rectangle!");
    }
}

struct Circle {}

impl Shape for Circle {
    fn draw(&self) {
        println!("draw a circle!");
    }
}

struct ShapeFactory;
impl ShapeFactory {
    fn new_shape(s: &ShapeType) -> Box<dyn Shape> {
        match s {
            ShapeType::Circle => Box::new(Circle {}),
            ShapeType::Rectangle => Box::new(Rectangle {}),
        }
    }
}

fn main() {
    let shape = ShapeFactory::new_shape(&ShapeType::Circle);
    shape.draw(); // output: draw a circle!

    let shape = ShapeFactory::new_shape(&ShapeType::Rectangle);
    shape.draw(); // output: draw a rectangle!
}

simonsan avatar Feb 22 '21 11:02 simonsan

Tracking discussion on merging: https://github.com/lpxxn/rust-design-pattern/issues/7

simonsan avatar Feb 22 '21 11:02 simonsan

Another example can be found here: https://web.archive.org/web/20210222121736/https://chercher.tech/rust/factory-design-pattern-rust

simonsan avatar Feb 22 '21 12:02 simonsan