jack06215
8/21/2017 - 6:10 AM

C++ command design pattern

C++ command design pattern

#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;
};

class CoffeeMachine
{
public:
  typedef std::vector<std::function<void()>> OrderQ;
  OrderQ orders;
  
  CoffeeMachine()
    : orders()
  {}
  
  void request(OrderQ::value_type order)
  {
    orders.push_back(order);
  }
  
  void start()
  {
    for(auto const& order : orders) { order(); }
    orders.clear();
  }
};

int main() 
{
  CoffeeMachine coffeeMachine;
      CaffeineBeverage coffee(
        [] { return Recipes::amountWaterMl(150); }, &Recipes::brewCoffee);
    CaffeineBeverage tea(
        [] { return Recipes::amountWaterMl(200); }, &Recipes::brewTea);
  
  coffeeMachine.request([&]{ coffee.prepare(); });
  coffeeMachine.request([&]{ tea.prepare(); });
  coffeeMachine.start();
  
  return 0;
}