-
Notifications
You must be signed in to change notification settings - Fork 111
/
factory.rs
44 lines (35 loc) · 931 Bytes
/
factory.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//! 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!
}