-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfactory.cpp
80 lines (67 loc) · 2.04 KB
/
factory.cpp
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Factory design pattern
#include <iostream>
#include <memory>
#include <string>
// interface for common products that will be created by the factory
struct IFruit {
virtual std::string get_name() const = 0;
virtual ~IFruit() = default;
};
// concrete product
class Apple : public IFruit {
public:
std::string get_name() const override { return "apple"; }
};
// concrete product
class BigApple : public Apple {
public:
std::string get_name() const override { return "big apple"; }
};
// concrete product
class Orange : public IFruit {
public:
std::string get_name() const override { return "orange"; }
};
// concrete factory, deleted constructor
// creates products via static make_fruit
class FruitFactory {
public:
FruitFactory() = delete;
std::unique_ptr<IFruit> static make_fruit(const std::string& fruit) {
if (fruit == "apple") {
return std::make_unique<Apple>();
} else if (fruit == "big apple") {
return std::make_unique<BigApple>();
} else if (fruit == "orange") {
return std::make_unique<Orange>();
}
return nullptr;
}
};
int main() {
std::unique_ptr<IFruit> fruit;
fruit = FruitFactory::make_fruit("apple");
if (fruit) {
std::cout << "Making: " << fruit->get_name() << '\n';
} else {
std::cout << "Sorry, we don't have " << fruit->get_name() << '\n';
}
fruit = FruitFactory::make_fruit("big apple");
if (fruit) {
std::cout << "Making: " << fruit->get_name() << '\n';
} else {
std::cout << "Sorry, we don't have " << fruit->get_name() << '\n';
}
fruit = FruitFactory::make_fruit("orange");
if (fruit) {
std::cout << "Making: " << fruit->get_name() << '\n';
} else {
std::cout << "Sorry, we don't have " << fruit->get_name() << '\n';
}
fruit = FruitFactory::make_fruit("banana");
if (fruit) {
std::cout << "Making an " << fruit->get_name() << '\n';
} else {
std::cout << "Sorry, this fruit is too exotic to make!\n";
}
}