-
Notifications
You must be signed in to change notification settings - Fork 0
/
abstract_factory_v1.cc
79 lines (64 loc) · 1.64 KB
/
abstract_factory_v1.cc
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
//
// Design pattern # Abstract factory
// - A wrapper around the creation of object in a single call.
//
// g++ -std=c++17 -Wall -Wextra -o abstract_factory_v1 abstract_factory_v1.cc
//
#include <iostream>
#include <memory>
enum class Type {
BLACK, LATTE
};
struct Coffee {
virtual Type get_type() = 0;
virtual void prepare() = 0;
};
struct BlackCoffee: Coffee {
private:
Type type = Type::BLACK;
friend class HotCoffeeFactory;
// Keep it private to avoid creation of object outside the factory
BlackCoffee() {}
public:
Type get_type() override { return type; };
void prepare() override {
std::cout << "make coffee # black\n";
}
};
struct LatteCoffee: Coffee {
private:
Type type = Type::LATTE;
friend class HotCoffeeFactory;
// Keep it private to avoid creation of object outside the factory
LatteCoffee() {}
public:
Type get_type() override { return type; };
void prepare() override {
std::cout << "make coffee # latte\n";
}
};
// A factory to create objects
struct AbstractFactory {
virtual std::unique_ptr<Coffee> make(Type type) = 0;
};
struct HotCoffeeFactory: AbstractFactory {
std::unique_ptr<Coffee> make(Type type) override {
if (type == Type::BLACK)
return std::unique_ptr<Coffee>(new BlackCoffee());
else if (type == Type::LATTE)
return std::unique_ptr<Coffee>(new LatteCoffee());
return nullptr;
}
};
//
// Entry function
//
int main() {
std::cout << "Design pattern # Abstract factory\n";
auto factory = std::make_unique<HotCoffeeFactory>();
auto obj1 = factory->make(Type::BLACK);
obj1->prepare();
auto obj2 = factory->make(Type::LATTE);
obj2->prepare();
return 0;
}