title: Strategy Pattern with Anonymous Function Closure
body: <p>I want to implement the Stategy Pattern using Closures in php. The main advantage of using closure is to reduce the amount of boilerplate and code needed by creating additional classes. Usually the pattern looks like this:</p>
  
  <pre><code>interface StateDiscountCalculatorInterface
  {
      public function calculateDiscount($amount);
  }
  
  
  class NewYorkStateStrategy implement StateDiscountCalculatorInterface
  {
      public function calculateDiscount($amount)
      {
          // .... about 20 lines of code
      }
  }
  
  class CaliforniaStateStrategy implement StateTaxCalculatorInterface
  {
      public function calculateDiscount($amount)
      {
         // .... about 20 lines of code that's different from New York State Strategy
      }
  }
  
  class stateTaxContext
  {
      private $stategy;
  
      public function setStrategy(StateDiscountCalculatorInterface $strategy)
      {
          $this-&gt;strategy = $strategy;
      }
  
      public function getDiscount(array $amount)
      {
          return $this-&gt;strategy-&gt;calculateDiscount($amount);
      }
  
  }
  </code></pre>
  
  <p>The version below is with a closure implementing a php functional interface. Is this the right way to do this?</p>
  
  <pre><code>interface StateDiscountCalculatorInterface
  {
      public function calculateDiscount($amount);
  }
  
  
  class stateTaxContext
  {
      private $newYorkStateStrategy;
      private $californiaStateStrategy;
      private $state;
  
      public function __construct()
      {
          $this-&gt;newYorkStateStrategy = function () implements StateDiscountCalculatorInterface {
              ...NewYorkStateStrategy class is replaced with code here
          };
  
          $this-&gt;californiaStateStrategy = function () implements StateDiscountCalculatorInterface {
              ...CaliforniaStateStrategy class is replaced with code here
          };
      }
  
      public function getDiscount(array $amount)
      {
          if($this-&gt;state==='california')
          {
              $this-&gt;californiaStateStrategy-&gt;calculateDiscount($amount);
          }
      }
  
  }
  </code></pre>