jack06215

[tutorial] Strategy pattern

Jul 17th, 2020 (edited)
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. // c++ -std=c++11 -Wall ./strategy_cpp11.cpp  -o strategy_cpp11
  2. #include <iostream>
  3. #include <vector>
  4. #include <functional>
  5.  
  6. class Recipes {
  7. public:
  8.     static void brewCoffee() { std::cout << "dripping Coffee through filter\n"; }
  9.     static void brewTea() { std::cout << "steeping Tea\n"; }
  10.  
  11.     static int amountWaterMl(int ml) { return ml; }
  12.  
  13. };
  14.  
  15. class CaffeineBeverage {
  16. public:
  17.     CaffeineBeverage(std::function<int()> amountWaterMl, std::function<void()> brew)
  18.         : _amountWaterMl(amountWaterMl)
  19.         , _brew(brew)
  20.           {}
  21.  
  22.     void prepare() {
  23.         boilWater(_amountWaterMl());
  24.         _brew();
  25.         pourInCup();
  26.     }
  27.  
  28. private:
  29.     void boilWater(int ml) { std::cout << "boiling " << ml << " water\n"; }
  30.     void pourInCup() { std::cout << "pour in cup\n"; }
  31.     std::function<int()> _amountWaterMl;
  32.     std::function<void()> _brew;
  33. };
  34.  
  35. int main() {
  36.     CaffeineBeverage coffee(
  37.         [] { return Recipes::amountWaterMl(150); }, &Recipes::brewCoffee);
  38.     CaffeineBeverage tea(
  39.         [] { return Recipes::amountWaterMl(200); }, &Recipes::brewTea);
  40.  
  41.     using Beverages = std::vector<CaffeineBeverage*>;
  42.     Beverages beverages;
  43.  
  44.     beverages.push_back(&coffee);
  45.     beverages.push_back(&tea);
  46.  
  47.     for(auto &beverage : beverages) {
  48.         beverage->prepare();
  49.     }
  50. }
Add Comment
Please, Sign In to add comment