Design Pattern Examples
Overview of object-oriented design patterns
Visitor_Exercise.cpp
Go to the documentation of this file.
1
6
7#include <iostream>
8
9#include "helpers/formatstring.h"
10
11#include "Visitor_Exercise.h"
13#include "Visitor_Village.h"
14
15
17{
18
35 // ! [Using Visitor in C++]
37 {
38 std::cout << std::endl;
39 std::cout << "Visitor Exercise" << std::endl;
40
41 std::cout << " Creating Village" << std::endl;
42 std::unique_ptr<Visitor_Village> village = std::make_unique<Visitor_Village>();
43 village->LoadVillage();
44
45 OrderVisitor visitor(StringList{ "hamburger" });
46 std::cout
47 << Helpers::formatstring(" Ordering a hamburger from a shop in the %s",
48 village->Name.c_str())
49 << std::endl;
50 // Visit all shops and place an order for a hamburger at the shop
51 // that sells them. We don't know which shop it is and we don't
52 // need to know until we receive the order.
53 village->Accept(&visitor);
54 if (!visitor.ItemsReceived.empty())
55 {
56 // We are expecting only a single item
57 std::cout
58 << Helpers::formatstring(" We received a %s from %s.",
59 visitor.ItemsReceived[0].c_str(),
60 visitor.ShopNameReceivedFrom.c_str())
61 << std::endl;
62 }
63 else
64 {
65 std::cout << " Failed to receive a hamburger" << std::endl;
66 }
67
68 std::cout << " Done." << std::endl;
69 }
70 // ! [Using Visitor in C++]
71
72} // end namespace
Implementation of the OrderVisitor class used in the Visitor Pattern.
A visitor used for ordering items from various shops. The user starts with an instance of this class ...
Declaration of the Visitor_Exercise() function as used in the Visitor Pattern.
Declaration of the Visitor_Village class used in the Visitor Pattern.
std::vector< std::string > StringList
Typedef for a vector of std::string.
The namespace containing all Design Pattern Examples implemented in C++.
void Visitor_Exercise()
Example of using the Visitor design pattern.
std::string formatstring(const char *fmt,...)
Use the given string and arguments to return a buffer containing the formatted string....