首頁 >後端開發 >php教程 >程式碼皆來自《PHP設計模式》一書

程式碼皆來自《PHP設計模式》一書

WBOY
WBOY原創
2016-07-25 09:08:46841瀏覽
程式碼皆來自《PHP設計模式》一書
  1. ?/**
  2. * 轉自《PHP設計模式》 第六章: 裝飾器模式
  3. *
  4. * 裝飾器設計模式適用於下列工作場合: 需求變化是快速且細小的,而且幾乎不影響應用程式的其他部分。 ()
  5. * 使用裝飾器設計模式設計類別的目標是: 不必重寫任何現有的功能性程式碼,而是對某個基於物件套用增量變更。
  6. * 裝飾器設計模式採用這樣的建構方式: 在主程式碼流中應該能夠直接插入一個或多個變更或「裝飾」目標物件的裝飾器,同時不影響其他程式碼流。
  7. *
  8. */
  9. class CD {
  10. public $trackList;
  11. public function __con ( ) {
  12. $this->trackList = array();
  13. }
  14. public function addTrack($track) {
  15. $this->trackList[] = $track;
  16. }
  17. public function getTrackList() {
  18. $output = '';
  19. foreach ($this->trackList as $num => $track) {
  20. $output . = ($num + 1) 。 ") {$track}.";
  21. }
  22. return $output;
  23. }
  24. }
  25. $tracksFroExternalSource = array("這代表什麼", " Brr ", "再見");
  26. $myCD = new CD();
  27. foreach ($tracksFroExternalSource as $track) {
  28. $myCD->addTrack($track);
  29. }
  30. print "CD 包含:{$myCD->getTrackList()}n";
  31. /**
  32. * 需求發生小變化: 要求每個輸出的參數都採用大寫形式. 對於這麼小的變化而言, 最佳的做法並非修改基類或創建父- 子關係,
  33. 而是創建一個基於裝飾器設計模式的物件。
  34. *
  35. */
  36. class CDTrackListDecoratorCaps {
  37. private $_cd ;
  38. public function __construct(CD $cd) {
  39. $this->_cd = $cd;
  40. }
  41. public function makeCaps() {
  42. foreach ($ this->_cd->trackList as & $track) {
  43. $track = strtoupper($track);
  44. }
  45. }
  46. }
  47. $myCD = new CD() ;
  48. foreach ($tracksFroExternalSource as $track) {
  49. $myCD->addTrack($track);
  50. }
  51. //新增以下程式碼實作輸出參數採用大寫形式
  52. $myCDCaps = new CDTrackListDecoratorCaps($myCD);
  53. $myCDCaps->makeCaps();
  54. print "The CD contains:{$myCD->getTrackList() }n";
  55. /* Decorator.class.php 結束*/
  56. /* 定位檔Design/Decorator.class.php */
複製程式碼
  1. ?/**
  2. * 轉自《PHP設計模式》 第七章: 委託模式
  3. * 當一個物件包含複雜單一獨立的,必須基於判決執行的功能性的若干部分時,最佳的方法是適用基於委託設計模式的對象。
  4. *
  5. */
  6. /**
  7. * 範例: Web網站具有建立MP3檔案播放清單的功能, 也具有選擇以 M3U 或 PLS 格式下載播放清單的功能。
  8. *
  9. * 以下程式碼範例展示常規與委託兩種模式實作
  10. *
  11. */
  12. //常數實現
  13. class 播放清單{
  14. private $_songs;
  15. public function __construct() {
  16. $this->_songs = array();
  17. }
  18. public function addSong($location, $title) {
  19. $public function addSong($location, $title) {
  20. $
  21. $
  22. $
  23. $
  24. $
  25. $
  26. $
  27. $ Song = array("location" => $location, "title" => $title);
  28. $this->_songs[] = $song;
  29. }
  30. public function getM3U() {
  31. $m3u = "#EXTM3Unn";
  32. foreach ($this->_songs as $song) {
  33. $m3u .= "#EXTINF: -1, { $song['titletle ']}n";
  34. $m3u .= "{$song['location']}n";
  35. }
  36. return $m3u;
  37. }
  38. public function getPLS() {
  39. $pls = "[playlist]]nNumberOfEntries = ".數($this->_songs) 。 => $song) {
  40. $counter = $songCount + 1;
  41. $pls .= "檔案{$ counter} = {$song['location']}n";
  42. $pls .= "標題{$counter} = {$song['title']}n";
  43. $pls .= "LengthP {$counter} = -1 nn";
  44. }
  45. return $請;
  46. }
  47. }
  48. $playlist = new Playlist();
  49. $playlist->addSong("/home/aaron/music/brr.mp3", " Brr");
  50. $playlist->addSong("/home/aaron/music/goodbye.mp3", "再見");
  51. $externalRetrievedType = "pls";
  52. if ($externalRetrievedType == "pls") {
  53. $playlistContent = $playlist->getPLS();
  54. } else {
  55. $playlistContent = $playlist->getM3U();
  56. }
  57. echo $playlistContent;
  58. //委託實作模式
  59. {
  60. private $_songs;
  61. private $_tyepObject;
  62. public function __construct($type) {
  63. $this->_songs = array(); $this->_tyepObject = new $object;
  64. }
  65. public function addSong($location, $title) {
  66. $歌曲 = array("位置" => $位置, "標題" => $title);
  67. $this->_songs[] = $song;
  68. }
  69. public function getPlaylist() {
  70. $playlist = $this->_tyepObject->; getPlaylist($this->_songs);
  71. return $playlist;
  72. }
  73. }
  74. class m3uPlaylist {
  75. public function getPlaylist($songs) {
  76. $m3u = "#EXTM3Unn";
  77. foreach ($songs as $song) {
  78. $m3u .= "#EXTINF: -1, {$song['title']}n";
  79. $ m3u .= "{$song['location']}n";
  80. }
  81. return $m3u;
  82. }
  83. }
  84. class plsPlaylist {
  85. public function getPlaylist($songs) {
  86. $pls = "[playlist]]nNumberOfEntries = ".計數($歌曲) . "nn";
  87. foreach ($songs as $songCount => $song) {
  88. $counter = $songCount + 1;
  89. $pls .= "檔案{$counter} = { $歌曲['location']}n";
  90. $pls .= "標題{$counter} = {$song['title']}n";
  91. $pls .= "LengthP{$counter} = -1 nn";
  92. }
  93. return $pls;
  94. }
  95. }
  96. $externalRetrievedType = "pls";
  97. $playlist = new newPlaylist( $ externalRetrievedType);
  98. $playlist->addSong("/home/aaron/music/brr.mp3", "Brr");
  99. $playlist->addSong("/home/aaron) /music /goodbye.mp3", "再見");
  100. $playlistContent = $playlist->getPlaylist();
echo $playlistContent;/* End Delegate.class .php 的*/
/* 定位檔案Design/Delegate.class.php */ 複製程式碼
  1. ?/**
  2. * 轉自 《PHP設計模式》 第八章: 外觀模式
  3. * 外觀設計模式的目標是: 控制外部錯綜複雜的關係, 並且提供簡單的介面以利用上述組件的能力。
  4. * 為了隱藏複雜的,執行業務流程某個步驟所需的方法和邏輯群組,就應使用基於外觀設計模式的類別。
  5. *
  6. */
  7. /**
  8. * 程式碼範例: 取得CD對象,對其所有屬性應用大寫形式,並且建立一個要提交給Web服務的,格式完整的XML文件。
  9. *
  10. */
  11. class CD {
  12. public $tracks = array();
  13. public $band = '';
  14. public $title = '';
  15. public function __construct($tracks, $band, $title) {
  16. $this->tracks = $tracks;
  17. $this->band = $band;
  18. $this->title = $title;
  19. }
  20. }
  21. }
  22. }
  23. class CDUpperCase {
  24. public static function makeString(CD $cd, $type) {
  25. $cd->$type = strtoupper($cd->$type);
  26. }
  27. public static function makeArray(CD $cd, $type) {
  28. $cd->$type = array_map("strtoupper", $cd->$type);
  29. }
  30. }
  31. class CDMakeXML {
  32. public static function create(CD $cd) {
  33. $doc = new DomDocument();
  34. $root = $doc->createElement(" CD");
  35. $root = $doc->appendChild($root);
  36. $title = $doc->createElement("TITLE", $cd->title);
  37. $ title = $root->appendChild($title);
  38. $band = $doc->createElement("BAND", $cd->; band);
  39. $band = $root->appendChild ($band);
  40. $tracks = $doc->createElement("TRACKS");
  41. $tracks = $root->appendChild($tracks);
  42. foreach ($ cd->tracks as $track) {
  43. $track = $doc->createElement("TRACK", $track);
  44. $track = $tracks->appendChild($track);
  45. }
  46. return $doc->saveXML();
  47. }
  48. }
  49. class WebServiceFacade {
  50. public static function makeXMcade {
  51. public static function makeXMcade {
  52. public static function makeXMLCa(CD) CDUpperCase::makeString($cd, "標題");
  53. CDUpperCase::makeString($cd, "樂團");
  54. CDUpperCase::makeArray($cd, "tracks");
  55. $xml = CDMakeXML::create($cd);
  56. return $xml;
  57. }
  58. }
  59. $tracksFromExternalSource = array("這代表什麼", "Brr", "再見");
  60. $band = " 再次不會";
  61. $title = " 浪費辮子肋骨";
  62. $cd = 新CD($tracksFromExternalSource, $band, $title);
$xml = WebServiceFacade::makeXMLCall($cd);
choechoe $ xml;
/* Facade.class.php 結束*//* 定位檔案Design/Facade.class.php */複製程式碼
  1. ?/**
  2. * 轉自《PHP設計模式》 第九章: 工廠模式
  3. * 工廠設計模式: ​​提供獲取某個對象的新實例的一個接口, 同時使調用代碼避免確定實際實例化基類的步驟
  4. *
  5. */
  6. //基礎標準CD類別
  7. class CD {
  8. public $ tracks = array();
  9. public $band = '';
  10. public $title = '';
  11. public function __construct() {}
  12. public function setTitle($ title) {
  13. $this->title = $title;
  14. }
  15. public function setBand($band) {
  16. $this->band = $band;
  17. }
  18. public function addTrack($track) {
  19. $this->tracks[] = $track;
  20. }
  21. }
  22. //增強型CD , 與標準CD的唯一不同是寫至CD的第一個track是資料track("DATA TRACK")
  23. class enhadcedCD {
  24. public $tracks = array();
  25. public $ band = '';
  26. public $title = '';
  27. public function __construct() {
  28. $this->tracks = "DATA TRACK";
  29. }
  30. public function setTitle($title) {
  31. $this->title = $title;
  32. }
  33. public function setBand($band) {
  34. $this->band = $band ;
  35. }
  36. public function addTrack($track) {
  37. $this->tracks[] = $track;
  38. }
  39. }
  40. /CD工廠類,實現對以上兩個類別具體實例化操作
  41. class CDFactory {
  42. public static function create($type) {
  43. $class = strtolower($type) . "CD";
  44. return new $class;
  45. }
  46. }
  47. //實例操作
  48. $type = "enhadced";
  49. $cd = CD$type = "enhadced";
  50. $cd = CDyy: :create($type);
  51. $tracksFromExternalSource = array("What It Means", "Brr", "Goodbye");
  52. $cd->setBand("Never Again") ;
  53. $cd->setTitle("Waste of a Rib");
  54. foreach ($tracksFromExternalSource as $track) {
  55. $cd->addTrack($track);
  56. }
/* End of Factory.class.php */
/* End of file Design/Factory.class.php */
複製程式碼
  1. ?/**
  2. * 轉自《PHP設計模式》 第十章: 解釋器模式
  3. * 解釋器: 解釋器設計模式用於分析一個實體的關鍵元素,並且針對每個元素都提供自己的解釋或相應的動作。
  4. * 解譯器設計模式最常用於PHP/HTML 模板系統。
  5. *
  6. */
  7. class User {
  8. protected $_username = "";
  9. public function __construct($username) {
  10. $this->_username = $username;
  11. }
  12. public function getProfilePage() {
  13. $profile = "

    Iike = "

    Iike Never Again !

    ";
  14. $profile .= "I love all of their songs. My favorite CD:
    ";
  15. $profile .= "{{myCD.getTitle}}! !";
  16. return $profile;
  17. }
  18. }
  19. class userCD {
  20. protected $_user = NULL;
  21. protected $_user = NULL;
  22. public function setUser(User $user) {
  23. $this->_user = $user;
  24. }
  25. public function getTitle() {
  26. $title = "Waste of a Rib";
  27. return $title;
  28. }
  29. }
  30. class userCDInterpreter {
  31. protected $_user = NULL;
  32. public function sUser(User fUser' ) {
  33. $this->_user = $user;
  34. }
  35. public function getInterpreted() {
  36. $profile = $this->_user->getProfilePage();
  37. $profile = $this->_user->getProfilePage();
  38. if (preg_match_all('/{{myCD.(.*?)}}/', $profile, $triggers, PREG_SET_ORDER)) {
  39. $replacements = array();
  40. $replacements[] = $trigger[1];
  41. }
  42. $replacements = array_unique($replacements);
  43. $myCD = new userCD();
  44. $myCD->setUser($this->_user);
  45. foreach ($replacements as $replacement) {
  46. $profile = str_replace("{{myCD.{ $replacement}}}", call_user_func(array($myCD, $replacement)), $profile);
  47. }
  48. }
  49. return $profile;
  50. }
  51. }
  52. $username = "aaron";
  53. $user = new User($username);
  54. $interpreter = new userCDInterpreter();
  55. $interpreter->setUser($user );
print "

{$username}'s Profile

";
print $interpreter->getInterpreted();/* End of Interpreter. class.php */
/* Location the file Design/Interpreter.class.php */複製程式碼
  1. ?/**
  2. * 轉自《PHP設計模式》 第十一章: 迭代器模式
  3. * 迭代器:迭代器設計模式可幫助建構特定對象, 那些物件能夠提供單一標準介面循環或迭代任何類型的可計數數據。
  4. * 處理需要遍歷的可計數資料時, 最佳的解決方法是建立一個基於迭代器設計模式的物件。
  5. *
  6. */
  7. class CD {
  8. public $band = "";
  9. public🎜>
  10. public $band = "";
  11. public $title = "";
  12. public $trackList = array();
  13. public $trackList = array();
  14. public function __construct($band, $title) {
  15. $this->band = $band;
  16. $
  17. $ this->title = $title;
  18. }
  19. public function addTrack($track) {
  20. $this->trackList[] = $track;
  21. }
  22. } }
  23. }
  24. class CDSearchByBandIterator 實作迭代器{
  25. private $_CDs = array();
  26. private $_valid = FALSE;
  27. public function __struct($struct) $db = mysql_connect("localhost", "root", "root");
  28. mysql_select_db("test");
  29. $sql = "選擇CD.id, CD.band, CD.title 、tracks.tracknum、tracks.title as tracktitle ";
  30. $sql .= "從CD 左連接CD.id = Tracks.cid 上的曲目";
  31. $sql .= "其中band = ' 」。 mysql_real_escape_string($bandName) 。 ;
  32. $cd = NULL;
  33. while ($result = mysql_fetch_array($results)) {
  34. if ($result["id"] !== $cdID) {
  35. if ( !is_null($cd) )) {
  36. $this->_CDs[] = $cd;
  37. }
  38. $cdID = $result['id'];
  39. $cd = 新CD($result ['band'], $result['title']);
  40. }
  41. $cd->addTrack($result['tracktitle']);
  42. }
  43. }
  44. $this->_CDs[] = $cd;
  45. }
  46. public function next() {
  47. $this->_valid = (next($this->_CDs ) FALSE : TRUE;
  48. }
  49. public function rewind() {
  50. $this->_valid = (reset($this->_CDs) === FALSE) FALSE : TRUE;
  51. }
  52. public function valid() {
  53. return $this->_valid;
  54. }
  55. public function current() {
  56. return current($this-> _CDs);
  57. }
  58. public function key() {
  59. return key($this->_CDs);
  60. }
  61. }
  62. $queryItem = " Never Again";
  63. $cds = new CDSearchByBandIterator($queryItem);
  64. print "

    找到以下CD

    " ;
  65. print "";
  66. foreach ($ cds as $cd) {
  67. print "
  68. Band Ttile Num Tracks
    {$cd->band} {$cd ->標題} ";
  69. 列印統計($cd-> trackList)。定位檔Design/Iterator.class.php */
  70. 複製程式碼
    1. ?/**
    2. * 轉自《PHP設計模式》 第十二章: 中介者模式
    3. * 中介者: 中介者設計莫用於開發一個對象,這個對象能夠在類似對象相互之間不直接交互的情況下傳送或調節這些物件的集合的修改
    4. * 處理具有類似屬性並且屬性需要保持同步的非耦合物件時,最佳的做法是使用基於中介者設計模式的物件。
    5. *
    6. */
    7. /**
    8. * 測試案例描述:範例程式碼不僅允許樂隊進入和管理他們的音樂合集,而且還允許樂隊更新他們的配置文件,修改樂隊相關信息以及更新其CD信息
    9. *        現在,藝術家可上傳MP3集合並從Web站點撤下CD。 因此, Web網站需要保持相對應的CD和MP3彼此同步。
    10. *
    11. */
    12. //CD類
    13. 類CD {
    14. public $band = '';
    15. public $title = '';
    16. protected $_mediator;
    17. public function __construct(MusicContainerMediator $mediator = NULL) {
    18. $this->_mediator = $mediator;
    19. }
    20. public function save() {
    21. //具體實作待定
    22. var_dump($this);
    23. }
    24. public function changeBandName($bandname) {
    25. if ( !is_null($this->_mediator)) {
    26. $this->_mediator->change($this, array(" band" => $ bandname));
    27. }
    28. $this->band = $bandname;
    29. $this->save();
    30. }
    31. }
    32. //MP3Archive類別
    33. class MP3Archive {
    34. protected $_mediator;
    35. public function __construct(MusicContainerMediator $mediator = NULL) {
    36. $this->_media_media; >
    37. public function save() {
    38. //具體實作待定
    39. var_dump($this);
    40. }
    41. public function changeBandName( $bandname) {
    42. public function changeBandName( $bandname) {
    43. if (🎜> if ( !is_null($this->_mediator)) {
    44. $this->_mediator->change($this, array("band" => $bandname)) ;
    45. }
    46. $this->band = $bandname;
    47. $this->save();
    48. }
    49. }
    50. //加入者類別
    51. class MusicContainerMediator {
    52. protected $_containers = $_containers = array();
    53. public function __construct() {
    54. $this->_containers[] = "CD";
    55. $this->_containers[] = "MP3Archive";
    56. }
    57. public function change($originalObject, $newValue) {
    58. $title = $originalObject->title;
    59. $band = $originalObject->band;
    60. foreach ($each ($each this->_containers as $container) {
    61. if ( ! ($originalObject instanceof $container)) {
    62. $object = new $container;
    63. $object->title = $title;
    64. $object->band = $band;
    65. foreach ($newValue as $key => $val) {
    66. $object->$key = $val;
    67. }
    68. $object->save();
    69. }
    70. }
    71. }
    72. }
    73. //測試實例
    74. $titleFromDB = "Waste of a Rib";
    75. $bandFromDB = "Never Again";
    76. $
    77. $bandFromDB = "Never Again";
    78. $
    79. $ mediator = new MusicContainerMediator();
    80. $cd = new CD($mediator);
    81. $cd->title = $titleFromDB;
    82. $cd->band = $bandFromDB;
    83. $cd->changeBandName("Maybe Once More");
    /* Mediator.class.php 結尾*/
    /* 定位檔案Design /Mediator.class.php */
    複製程式碼
    1. /*
    2. SQLyog 企業版- MySQL GUI v8.14
    3. MySQL - 5.1.52-community : 資料庫- 測驗
    4. ******* * ************************************************* ********* ************
    5. */
    6. /*!40101 設定名稱utf8 */;
    7. /* !40101 SET SQL_MODE=''*/ ;
    8. /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
    9. /*!40014 CHECKS =0 */;
    10. / *!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
    11. /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES=/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES 🎜>/*表`的表結構cd` */
    12. 如果存在`cd`,則刪除表;
    13. 建立表`cd` (
    14. `id` int(8 ) NOT NULL AUTO_INCRMENT,
    15. `band` varchar(500) COLLATE latin1_bin NOT NULL DEFAULT '',
    16. `title` varchar(500) COLLATE latin1_bin NOT NULLULL> `title` varchar(500) COLLATE latin1_bin NOT NULLULLFAULT ” ) DEFAULT NULL,
    17. `amount` int (8) DEFAULT NULL,
    18. PRIMARY KEY (`id`)
    19. ) ENGINE=InnoDB AUTO_INCRMENT=2 DEFAULT CHARSET=latin1 >/*表`cd` 的資料* /
    20. 插入`cd`(`id`,`band`,`title`,`bought`,`amount`) 值(1,'Never Again' ,'Waster of a Rib',1 ,98);
    21. /*表`tracks` 的表結構*/
    22. DROP TABLE IF EXISTS `tracks`;
    23. CREATE TABLE `tracks` (
    24. `cid` int(8) DEFAULT NULL,
    25. `tracknum` int(8) DEFAULT NULL,
    26. `title` varchar(500) COLLATE latin1_bin NN N NULL* 🎜>) ENGINE=InnoDB DEFAULT CHARSET= latin1 COLLATE=latin1_bin;
    27. /*表格`tracks` 的資料*/
    28. 插入`tracks`(`cid`,`racknum`,`,`racknum`,`,`racknum. title`) 值(1, 3,'這代表什麼'),(1,3,'Brr'),(1,3,'再見');
    29. /*!40101 SET SQL_MODE= @OLD_SQL_MODE */;
    30. /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
    31. /*!40014 SET UNIQUE_CHECKS=@OLD_UNI>/*!40014 SET UNIQUE_CHECKS=@OLD_UNIm.
    32. 複製程式碼
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn