-
Notifications
You must be signed in to change notification settings - Fork 111
/
factory.rs
46 lines (37 loc) · 904 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
45
46
/*
Factory method creational design pattern allows creating objects without having to specify the exact type of the object that will be created.
*/
trait Shap {
fn draw(&self);
}
enum ShapType {
Rectangle,
Circl,
}
struct Rectangle {}
impl Shap for Rectangle {
fn draw(&self) {
println!("draw a rectangle!");
}
}
struct Circl {}
impl Shap for Circl {
fn draw(&self) {
println!("draw a circl!");
}
}
struct ShapFactory;
impl ShapFactory {
fn new_shap(s: &ShapType) -> Box<dyn Shap> {
match s {
ShapType::Circl => Box::new(Circl {}),
ShapType::Rectangle => Box::new(Rectangle {}),
}
}
}
fn main() {
let shap = ShapFactory::new_shap(&ShapType::Circl);
shap.draw(); // output: draw a circl!
let shap = ShapFactory::new_shap(&ShapType::Rectangle);
shap.draw(); // output: draw a rectangle!
}