Created
January 1, 2021 07:16
-
-
Save devendranaga/344a5a8302dc9f7e709a5a3a88b91046 to your computer and use it in GitHub Desktop.
decorator c++ design pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <memory> | |
#include <string.h> | |
class AddOn { | |
public: | |
explicit AddOn(std::string description) { description_ = description; } | |
~AddOn() = default; | |
std::string getDescription() { return description_; } | |
private: | |
std::string description_; | |
}; | |
class Beverage { | |
public: | |
explicit Beverage(std::string description, std::shared_ptr<AddOn> &addon): description_(description), addon_(addon) { } | |
~Beverage() = default; | |
std::string getDescription() { return description_; } | |
std::string getAddOn() { return addon_->getDescription(); } | |
virtual double cost() = 0; | |
private: | |
std::string description_; | |
std::shared_ptr<AddOn> addon_; | |
}; | |
class Sugar : public AddOn { | |
public: | |
explicit Sugar() : AddOn("Sugar") { } | |
~Sugar() = default; | |
}; | |
class Milk : public AddOn { | |
public: | |
explicit Milk() : AddOn("Milk") { } | |
~Milk() = default; | |
}; | |
class HouseBlend : public Beverage { | |
public: | |
explicit HouseBlend(std::shared_ptr<AddOn> addon) : Beverage("HouseBlend", addon) { } | |
virtual ~HouseBlend() { } | |
double cost() { return 100; } | |
}; | |
class DarkRoast : public Beverage { | |
public: | |
explicit DarkRoast(std::shared_ptr<AddOn> addon) : Beverage("DarkRoast", addon) { } | |
virtual ~DarkRoast() { } | |
double cost() { return 200; } | |
}; | |
int main(int argc, char **argv) | |
{ | |
std::unique_ptr<Beverage> bev; | |
if (!strcmp(argv[1], "houseblend")) { | |
if (!strcmp(argv[2], "milk")) { | |
bev = std::make_unique<HouseBlend>(std::make_shared<Milk>()); | |
} | |
} else if (!strcmp(argv[1], "darkroast")) { | |
if (!strcmp(argv[2], "sugar")) { | |
bev = std::make_unique<DarkRoast>(std::make_shared<Sugar>()); | |
} | |
} | |
printf("cost of bev(%s) with (%s): %f\n", bev->getDescription().c_str(), bev->getAddOn().c_str(), bev->cost()); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment