-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtemplate-method.cpp
More file actions
80 lines (67 loc) · 1.76 KB
/
template-method.cpp
File metadata and controls
80 lines (67 loc) · 1.76 KB
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
/*!
* Example from Udemy course at
* https://www.udemy.com/course/patterns-cplusplus/
*/
#include <iostream>
#include <string>
/*!
* @brief Abstract Class
* Defines the skeleton of the algorithm
* that shall be implemented by subclasses
* to become particular algorithms.
*
* Note : Here, every method is pure virtual but we
* can provide default implementation if some
* parts of the algorithms are always the same.
*
* Note : We could also make some method non-virtual
* and not let clients override them if we have
* some parts of the algorithms that should not
* be modified.
*/
class Game
{
public:
explicit Game(int p_nb) : m_nb(p_nb) {}
void run()
{
start();
while ( !have_winner() ) { take_turn(); }
std::cout << "Player " << get_winner() << " wins.\n";
}
protected:
virtual void start () = 0;
virtual bool have_winner() = 0;
virtual void take_turn () = 0;
virtual int get_winner () = 0;
int m_cur{0};
int m_nb;
};
/*!
* @brief Concrete Class
* Implements the skeleton of the algorithm.
*/
class Chess : public Game
{
public:
explicit Chess() : Game{2} {}
protected:
void start() override { std::cout << "Starting a game of chess\n"; }
// The condition is silly, but you get the point.
bool have_winner() override { return m_turn == m_max; }
void take_turn () override
{
std::cout << "Turn " << m_turn++ << " taken by player " << m_cur << "\n";
m_cur = (m_cur + 1) % m_nb;
}
int get_winner () override { return m_cur; }
private:
int m_turn{ 0};
static const int m_max {10};
};
int main()
{
Chess chess;
chess.run();
return EXIT_SUCCESS;
}