Skip to content

Instantly share code, notes, and snippets.

@devendranaga
Created January 1, 2021 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devendranaga/344a5a8302dc9f7e709a5a3a88b91046 to your computer and use it in GitHub Desktop.
Save devendranaga/344a5a8302dc9f7e709a5a3a88b91046 to your computer and use it in GitHub Desktop.
decorator c++ design pattern
#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