Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Factory Method #224

Open
Tracked by #116
simonsan opened this issue Feb 22, 2021 · 2 comments
Open
Tracked by #116

Factory Method #224

simonsan opened this issue Feb 22, 2021 · 2 comments
Labels
A-pattern Area: Content about Patterns C-addition Category: Adding new content, something that didn't exist in the repository before C-needs discussion Area: Something that is not clear to everyone if it fixes something/adds valuable content

Comments

@simonsan
Copy link
Collaborator

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 simonsan added C-addition Category: Adding new content, something that didn't exist in the repository before A-pattern Area: Content about Patterns labels Feb 22, 2021
@simonsan
Copy link
Collaborator Author

Tracking discussion on merging: lpxxn/rust-design-pattern#7

@simonsan
Copy link
Collaborator Author

@simonsan simonsan added the C-needs discussion Area: Something that is not clear to everyone if it fixes something/adds valuable content label Feb 23, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-pattern Area: Content about Patterns C-addition Category: Adding new content, something that didn't exist in the repository before C-needs discussion Area: Something that is not clear to everyone if it fixes something/adds valuable content
Projects
None yet
Development

No branches or pull requests

1 participant