Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // c++ -std=c++11 -Wall ./strategy_cpp11.cpp -o strategy_cpp11
- #include <iostream>
- #include <vector>
- #include <functional>
- class Recipes {
- public:
- static void brewCoffee() { std::cout << "dripping Coffee through filter\n"; }
- static void brewTea() { std::cout << "steeping Tea\n"; }
- static int amountWaterMl(int ml) { return ml; }
- };
- class CaffeineBeverage {
- public:
- CaffeineBeverage(std::function<int()> amountWaterMl, std::function<void()> brew)
- : _amountWaterMl(amountWaterMl)
- , _brew(brew)
- {}
- void prepare() {
- boilWater(_amountWaterMl());
- _brew();
- pourInCup();
- }
- private:
- void boilWater(int ml) { std::cout << "boiling " << ml << " water\n"; }
- void pourInCup() { std::cout << "pour in cup\n"; }
- std::function<int()> _amountWaterMl;
- std::function<void()> _brew;
- };
- int main() {
- CaffeineBeverage coffee(
- [] { return Recipes::amountWaterMl(150); }, &Recipes::brewCoffee);
- CaffeineBeverage tea(
- [] { return Recipes::amountWaterMl(200); }, &Recipes::brewTea);
- using Beverages = std::vector<CaffeineBeverage*>;
- Beverages beverages;
- beverages.push_back(&coffee);
- beverages.push_back(&tea);
- for(auto &beverage : beverages) {
- beverage->prepare();
- }
- }
Add Comment
Please, Sign In to add comment