jack06215

[tutorial] Commend pattern

Jul 17th, 2020 (edited)
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <functional>
  4.  
  5.  
  6. class Recipes
  7. {
  8. public:
  9.     static void brewCoffee() { std::cout << "dripping Coffee through filter\n"; }
  10.     static void brewTea() { std::cout << "steeping Tea\n"; }
  11.  
  12.     static int amountWaterMl(int ml) { return ml; }
  13.  
  14. };
  15.  
  16. class CaffeineBeverage
  17. {
  18. public:
  19.     CaffeineBeverage(std::function<int()> amountWaterMl, std::function<void()> brew)
  20.         : _amountWaterMl(amountWaterMl)
  21.         , _brew(brew)
  22.     {}
  23.  
  24.     void prepare() {
  25.         boilWater(_amountWaterMl());
  26.         _brew();
  27.         pourInCup();
  28.     }
  29.  
  30. private:
  31.     void boilWater(int ml) { std::cout << "boiling " << ml << " water\n"; }
  32.     void pourInCup() { std::cout << "pour in cup\n"; }
  33.     std::function<int()> _amountWaterMl;
  34.     std::function<void()> _brew;
  35. };
  36.  
  37. class CoffeeMachine
  38. {
  39. public:
  40.     typedef std::vector<std::function<void()>> OrderQ;
  41.     OrderQ orders;
  42.  
  43.     CoffeeMachine()
  44.         : orders()
  45.     {}
  46.  
  47.     void request(OrderQ::value_type order)
  48.     {
  49.         orders.push_back(order);
  50.     }
  51.  
  52.     void start()
  53.     {
  54.         for (auto const& order : orders) { order(); }
  55.         orders.clear();
  56.     }
  57. };
  58.  
  59. int main()
  60. {
  61.     CoffeeMachine coffeeMachine;
  62.     CaffeineBeverage coffee([] { return Recipes::amountWaterMl(150); }, &Recipes::brewCoffee);
  63.     CaffeineBeverage tea([] { return Recipes::amountWaterMl(200); }, &Recipes::brewTea);
  64.  
  65.     coffeeMachine.request([&] { coffee.prepare(); });
  66.     coffeeMachine.request([&] { tea.prepare(); });
  67.     coffeeMachine.start();
  68.  
  69.     return 0;
  70. }
Add Comment
Please, Sign In to add comment