From ce8de9c03c1669456a2cb3fdf26a7053c0d555b3 Mon Sep 17 00:00:00 2001 From: Ian Dinwoodie Date: Mon, 29 Apr 2019 20:17:55 -0400 Subject: [PATCH] Added composite example source code. --- examples/structural/composite.cpp | 121 ++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 examples/structural/composite.cpp diff --git a/examples/structural/composite.cpp b/examples/structural/composite.cpp new file mode 100644 index 0000000..c9db826 --- /dev/null +++ b/examples/structural/composite.cpp @@ -0,0 +1,121 @@ +#include +#include +#include +#include + +class Employee +{ + public: + typedef std::shared_ptr ptr_t; + virtual std::string getName(void) = 0; + virtual void setSalary(float salary) = 0; + virtual float getSalary(void) = 0; + virtual std::string getRole(void) = 0; +}; + +class Developer : public Employee +{ + public: + Developer(const std::string& name, float salary) + : name_(name), salary_(salary), role_("Developer") + { + } + + std::string getName(void) + { + return name_; + } + + void setSalary(float salary) + { + salary_ = salary; + } + + float getSalary(void) + { + return salary_; + } + + std::string getRole(void) + { + return role_; + } + + private: + std::string name_; + float salary_; + std::string role_; +}; + +class Designer : public Employee +{ + public: + Designer(const std::string& name, float salary) + : name_(name), salary_(salary), role_("Designer") + { + } + + std::string getName(void) + { + return name_; + } + + void setSalary(float salary) + { + salary_ = salary; + } + + float getSalary(void) + { + return salary_; + } + + std::string getRole(void) + { + return role_; + } + + private: + std::string name_; + float salary_; + std::string role_; +}; + +class Organization +{ + public: + void addEmployee(Employee::ptr_t employee) + { + employees_.push_back(employee); + } + + float getNetSalaries(void) + { + float net = 0; + for (auto employee : employees_) { + net += employee->getSalary(); + } + + return net; + } + + private: + std::vector employees_; +}; + +int main() +{ + // Prepare the employees. + Employee::ptr_t jane = std::make_shared("Jane Doe", 50000); + Employee::ptr_t john = std::make_shared("John Doe", 45000); + + // Add them to the organization. + Organization org; + org.addEmployee(jane); + org.addEmployee(john); + + // Get the net salaries. + std::cout << org.getNetSalaries() << std::endl; // Output: 95000 + + return 0; +}