《PHP設計模式介紹》第三章 工廠模式(4)_PHP教程

      編輯Tag賺U幣
      教程Tag:暫無Tag,歡迎添加,賺取U幣!

      推薦:《PHP設計模式介紹》第二章 值對象模式
      在所有的最簡單的程序中,大多數對象都有一個標識,一個重要的商業應用對象,例如一個Customer或者一個SKU,有一個或者更多的屬性---id,name,email地址,這樣可以把它從同一個類的其他實例區分開

      所有這些測試Color類功能的行為都在正常和期望的環境下實現的。但是每一個設計精良的類都必須考慮邊界情況。例如, 被送入構造器執行的數值如果是負數,或者大于255的數值,或者根本不是數值,結果會出現什么呢?一個好的類定義應該適應測試中的多種邊界情況。

      function testColorBoundaries() {
      $color =& new Color(-1);
      $this->assertErrorPattern(‘/out.*0.*255/i’);
      $color =& new Color(1111);
      $this->assertErrorPattern(‘/out.*0.*255/i’);
      }

      注:assertErrorPattern
      assertErrorPattern() 作用是:將產生的php錯誤進行正確的正則表達式匹配。如果這個錯誤不匹配指定的模式, 將不通過測試。
      在那些測試的基礎上,Color類將得到更進一步改進:

      class Color {
      var $r=0;
      var $g=0;
      var $b=0;
      function Color($red=0, $green=0, $blue=0) {
      $red = (int)$red;
      if ($red < 0 || $red > 255) {
      trigger_error(“color ‘$color’ out of bounds, “
      .”please specify a number between 0 and 255”);
      }
      $this->r = $red;
      $green = (int)$green;
      if ($green < 0 || $green > 255) {
      trigger_error(“color ‘$color’ out of bounds, “
      .”please specify a number between 0 and 255”);
      }
      $this->g = $green;
      $blue = (int)$blue;
      if ($blue < 0 || $blue > 255) {
      trigger_error(“color ‘$color’ out of bounds, “
      .”please specify a number between 0 and 255”);
      }
      $this->b = $blue;
      }
      function getRgb() {
      return sprintf(‘#XXX’, $this->r, $this->g, $this->b);
      }
      }

      這個代碼通過了測試, 但是這種 " 剪切和粘貼 " 的風格有點使人厭倦。 在 TDD,一個經驗法則就是將編碼最簡單的實現,如果你兩次需要相同的代碼,可以將其改進,但不要復制代碼。 然而你往往需要三次或三次以上的一樣代碼。 因此我們可以提取一個方法即重構實現這個工作。

      注:重構 - 提取方法
      當你的代碼中有兩個或者兩個以上部分的代碼相似的時候, 可以將它們提取出來成為一個獨立的方法,并按它的用途命名。當你的類的方法代碼中頻頻出現相同的成分,提取代碼作為一個方法是非常有用的。

      class Color {
      var $r=0;
      var $g=0;
      var $b=0;
      function Color($red=0, $green=0, $blue=0) {
      $this->r = $this->validateColor($red);
      $this->g = $this->validateColor($green);
      $this->b = $this->validateColor($blue);
      }
      function validateColor($color) {
      $check = (int)$color;
      if ($check < 0 || $check > 255) {
      trigger_error(“color ‘$color’ out of bounds, “
      .”please specify a number between 0 and 255”);
      } else {
      return $check;
      }
      }
      function getRgb() {
      return sprintf(‘#XXX’, $this->r, $this->g, $this->b);
      }
      }

      分享:《PHP設計模式介紹》第一章 編程慣用法
      學習一門新的語言意味著要采用新的慣用法。這章將介紹或者可能重新強調一些慣用法。你會發現這些慣用法在你要在代碼中實現設計模式時候是非常有用的。 在這里總結的許多編程慣用法都是很值得

      來源:模板無憂//所屬分類:PHP教程/更新時間:2008-08-22
      相關PHP教程