程式碼皆來自《PHP設計模式》一書
- ?/**
- * 轉自《PHP設計模式》 第六章: 裝飾器模式
- *
- * 裝飾器設計模式適用於下列工作場合: 需求變化是快速且細小的,而且幾乎不影響應用程式的其他部分。 ()
- * 使用裝飾器設計模式設計類別的目標是: 不必重寫任何現有的功能性程式碼,而是對某個基於物件套用增量變更。
- * 裝飾器設計模式採用這樣的建構方式: 在主程式碼流中應該能夠直接插入一個或多個變更或「裝飾」目標物件的裝飾器,同時不影響其他程式碼流。
- *
- */
- class CD {
- public $trackList;
- public function __con ( ) {
- $this->trackList = array();
- }
-
- public function addTrack($track) {
- $this->trackList[] = $track;
- }
-
- public function getTrackList() {
- $output = '';
-
- foreach ($this->trackList as $num => $track) {
- $output . = ($num + 1) 。 ") {$track}.";
- }
-
- return $output;
- }
- }
-
- $tracksFroExternalSource = array("這代表什麼", " Brr ", "再見");
-
- $myCD = new CD();
- foreach ($tracksFroExternalSource as $track) {
- $myCD->addTrack($track);
- }
-
- print "CD 包含:{$myCD->getTrackList()}n";
-
- /**
- * 需求發生小變化: 要求每個輸出的參數都採用大寫形式. 對於這麼小的變化而言, 最佳的做法並非修改基類或創建父- 子關係,
- 而是創建一個基於裝飾器設計模式的物件。
- *
- */
- class CDTrackListDecoratorCaps {
- private $_cd ;
-
- public function __construct(CD $cd) {
- $this->_cd = $cd;
- }
-
- public function makeCaps() {
- foreach ($ this->_cd->trackList as & $track) {
- $track = strtoupper($track);
- }
- }
- }
-
- $myCD = new CD() ;
- foreach ($tracksFroExternalSource as $track) {
- $myCD->addTrack($track);
- }
-
- //新增以下程式碼實作輸出參數採用大寫形式
- $myCDCaps = new CDTrackListDecoratorCaps($myCD);
- $myCDCaps->makeCaps();
-
- print "The CD contains:{$myCD->getTrackList() }n";
-
- /* Decorator.class.php 結束*/
- /* 定位檔Design/Decorator.class.php */
複製程式碼
- ?/**
- * 轉自《PHP設計模式》 第七章: 委託模式
- * 當一個物件包含複雜單一獨立的,必須基於判決執行的功能性的若干部分時,最佳的方法是適用基於委託設計模式的對象。
- *
- */
-
- /**
- * 範例: Web網站具有建立MP3檔案播放清單的功能, 也具有選擇以 M3U 或 PLS 格式下載播放清單的功能。
- *
- * 以下程式碼範例展示常規與委託兩種模式實作
- *
- */
- //常數實現
- class 播放清單{
-
- private $_songs;
-
- public function __construct() {
- $this->_songs = array();
- }
-
- public function addSong($location, $title) {
- $public function addSong($location, $title) {
- $
- $
- $
- $
- $
- $
- $
- $ Song = array("location" => $location, "title" => $title);
- $this->_songs[] = $song;
- }
-
- public function getM3U() {
- $m3u = "#EXTM3Unn";
-
- foreach ($this->_songs as $song) {
- $m3u .= "#EXTINF: -1, { $song['titletle ']}n";
- $m3u .= "{$song['location']}n";
- }
-
- return $m3u;
- }
-
- public function getPLS() {
- $pls = "[playlist]]nNumberOfEntries = ".數($this->_songs) 。 => $song) {
- $counter = $songCount + 1;
- $pls .= "檔案{$ counter} = {$song['location']}n";
- $pls .= "標題{$counter} = {$song['title']}n";
- $pls .= "LengthP {$counter} = -1 nn";
- }
-
- return $請;
- }
- }
-
- $playlist = new Playlist();
-
- $playlist->addSong("/home/aaron/music/brr.mp3", " Brr");
- $playlist->addSong("/home/aaron/music/goodbye.mp3", "再見");
-
- $externalRetrievedType = "pls";
-
- if ($externalRetrievedType == "pls") {
- $playlistContent = $playlist->getPLS();
- } else {
- $playlistContent = $playlist->getM3U();
- }
-
- echo $playlistContent;
-
- //委託實作模式
- {
-
- private $_songs;
- private $_tyepObject;
-
- public function __construct($type) {
- $this->_songs = array(); $this->_tyepObject = new $object;
- }
-
- public function addSong($location, $title) {
- $歌曲 = array("位置" => $位置, "標題" => $title);
- $this->_songs[] = $song;
- }
-
- public function getPlaylist() {
- $playlist = $this->_tyepObject->; getPlaylist($this->_songs);
- return $playlist;
- }
- }
-
- class m3uPlaylist {
- public function getPlaylist($songs) {
- $m3u = "#EXTM3Unn";
-
- foreach ($songs as $song) {
- $m3u .= "#EXTINF: -1, {$song['title']}n";
- $ m3u .= "{$song['location']}n";
- }
-
- return $m3u;
- }
- }
-
- class plsPlaylist {
- public function getPlaylist($songs) {
- $pls = "[playlist]]nNumberOfEntries = ".計數($歌曲) . "nn";
-
- foreach ($songs as $songCount => $song) {
- $counter = $songCount + 1;
- $pls .= "檔案{$counter} = { $歌曲['location']}n";
- $pls .= "標題{$counter} = {$song['title']}n";
- $pls .= "LengthP{$counter} = -1 nn";
- }
-
- return $pls;
- }
- }
-
- $externalRetrievedType = "pls";
- $playlist = new newPlaylist( $ externalRetrievedType);
-
- $playlist->addSong("/home/aaron/music/brr.mp3", "Brr");
- $playlist->addSong("/home/aaron) /music /goodbye.mp3", "再見");
-
- $playlistContent = $playlist->getPlaylist();
echo $playlistContent; /* End Delegate.class .php 的*/ /* 定位檔案Design/Delegate.class.php */ 複製程式碼
- ?/**
- * 轉自 《PHP設計模式》 第八章: 外觀模式
- * 外觀設計模式的目標是: 控制外部錯綜複雜的關係, 並且提供簡單的介面以利用上述組件的能力。
- * 為了隱藏複雜的,執行業務流程某個步驟所需的方法和邏輯群組,就應使用基於外觀設計模式的類別。
- *
- */
- /**
- * 程式碼範例: 取得CD對象,對其所有屬性應用大寫形式,並且建立一個要提交給Web服務的,格式完整的XML文件。
- *
- */
- class CD {
-
- public $tracks = array();
- public $band = '';
- public $title = '';
-
- public function __construct($tracks, $band, $title) {
- $this->tracks = $tracks;
- $this->band = $band;
- $this->title = $title;
- }
-
- }
-
- }
-
- }
-
- class CDUpperCase {
-
- public static function makeString(CD $cd, $type) {
- $cd->$type = strtoupper($cd->$type);
- }
-
- public static function makeArray(CD $cd, $type) {
- $cd->$type = array_map("strtoupper", $cd->$type);
- }
- }
-
- class CDMakeXML {
-
- public static function create(CD $cd) {
- $doc = new DomDocument();
-
- $root = $doc->createElement(" CD");
- $root = $doc->appendChild($root);
-
- $title = $doc->createElement("TITLE", $cd->title);
- $ title = $root->appendChild($title);
-
- $band = $doc->createElement("BAND", $cd->; band);
- $band = $root->appendChild ($band);
-
- $tracks = $doc->createElement("TRACKS");
- $tracks = $root->appendChild($tracks);
-
- foreach ($ cd->tracks as $track) {
- $track = $doc->createElement("TRACK", $track);
- $track = $tracks->appendChild($track);
- }
-
- return $doc->saveXML();
- }
- }
-
- class WebServiceFacade {
-
- public static function makeXMcade {
-
- public static function makeXMcade {
-
- public static function makeXMLCa(CD) CDUpperCase::makeString($cd, "標題");
- CDUpperCase::makeString($cd, "樂團");
- CDUpperCase::makeArray($cd, "tracks");
-
- $xml = CDMakeXML::create($cd);
-
- return $xml;
- }
- }
-
- $tracksFromExternalSource = array("這代表什麼", "Brr", "再見");
- $band = " 再次不會";
- $title = " 浪費辮子肋骨";
-
- $cd = 新CD($tracksFromExternalSource, $band, $title);
-
$xml = WebServiceFacade::makeXMLCall($cd);
choechoe $ xml; /* Facade.class.php 結束*//* 定位檔案Design/Facade.class.php */複製程式碼
- ?/**
- * 轉自《PHP設計模式》 第九章: 工廠模式
- * 工廠設計模式: 提供獲取某個對象的新實例的一個接口, 同時使調用代碼避免確定實際實例化基類的步驟
- *
- */
- //基礎標準CD類別
- class CD {
-
- public $ tracks = array();
- public $band = '';
- public $title = '';
-
- public function __construct() {}
-
- public function setTitle($ title) {
- $this->title = $title;
- }
-
- public function setBand($band) {
- $this->band = $band;
- }
-
- public function addTrack($track) {
- $this->tracks[] = $track;
- }
-
- }
-
- //增強型CD , 與標準CD的唯一不同是寫至CD的第一個track是資料track("DATA TRACK")
- class enhadcedCD {
-
- public $tracks = array();
- public $ band = '';
- public $title = '';
-
- public function __construct() {
- $this->tracks = "DATA TRACK";
- }
-
- public function setTitle($title) {
- $this->title = $title;
- }
-
- public function setBand($band) {
- $this->band = $band ;
- }
-
- public function addTrack($track) {
- $this->tracks[] = $track;
- }
- }
-
- /CD工廠類,實現對以上兩個類別具體實例化操作
- class CDFactory {
-
- public static function create($type) {
- $class = strtolower($type) . "CD";
-
- return new $class;
- }
- }
-
- //實例操作
- $type = "enhadced";
-
- $cd = CD$type = "enhadced";
-
- $cd = CDyy: :create($type);
-
- $tracksFromExternalSource = array("What It Means", "Brr", "Goodbye");
-
- $cd->setBand("Never Again") ;
- $cd->setTitle("Waste of a Rib");
- foreach ($tracksFromExternalSource as $track) {
- $cd->addTrack($track);
- }
-
-
/* End of Factory.class.php */ /* End of file Design/Factory.class.php */
複製程式碼
-
-
- ?/**
- * 轉自《PHP設計模式》 第十章: 解釋器模式
- * 解釋器: 解釋器設計模式用於分析一個實體的關鍵元素,並且針對每個元素都提供自己的解釋或相應的動作。
- * 解譯器設計模式最常用於PHP/HTML 模板系統。
- *
- */
- class User {
-
- protected $_username = "";
-
- public function __construct($username) {
- $this->_username = $username;
- }
-
- public function getProfilePage() {
- $profile = "
Iike = "Iike Never Again ! ";
- $profile .= "I love all of their songs. My favorite CD:
";
- $profile .= "{{myCD.getTitle}}! !";
-
- return $profile;
- }
- }
-
- class userCD {
-
- protected $_user = NULL;
-
-
- protected $_user = NULL;
-
- public function setUser(User $user) {
- $this->_user = $user;
- }
-
- public function getTitle() {
- $title = "Waste of a Rib";
-
- return $title;
- }
- }
-
- class userCDInterpreter {
-
- protected $_user = NULL;
-
- public function sUser(User fUser' ) {
- $this->_user = $user;
- }
-
- public function getInterpreted() {
- $profile = $this->_user->getProfilePage();
- $profile = $this->_user->getProfilePage();
-
- if (preg_match_all('/{{myCD.(.*?)}}/', $profile, $triggers, PREG_SET_ORDER)) {
- $replacements = array();
- $replacements[] = $trigger[1];
- }
-
- $replacements = array_unique($replacements);
-
- $myCD = new userCD();
- $myCD->setUser($this->_user);
-
- foreach ($replacements as $replacement) {
- $profile = str_replace("{{myCD.{ $replacement}}}", call_user_func(array($myCD, $replacement)), $profile);
- }
- }
-
- return $profile;
- }
-
- }
-
- $username = "aaron";
- $user = new User($username);
- $interpreter = new userCDInterpreter();
- $interpreter->setUser($user );
print " {$username}'s Profile"; print $interpreter->getInterpreted(); /* End of Interpreter. class.php */ /* Location the file Design/Interpreter.class.php */複製程式碼
- ?/**
- * 轉自《PHP設計模式》 第十一章: 迭代器模式
- * 迭代器:迭代器設計模式可幫助建構特定對象, 那些物件能夠提供單一標準介面循環或迭代任何類型的可計數數據。
- * 處理需要遍歷的可計數資料時, 最佳的解決方法是建立一個基於迭代器設計模式的物件。
- *
- */
- class CD {
-
- public $band = "";
- public🎜>
- public $band = "";
- public $title = "";
- public $trackList = array();
-
- public $trackList = array();
-
- public function __construct($band, $title) {
- $this->band = $band;
- $
- $ this->title = $title;
- }
-
- public function addTrack($track) {
- $this->trackList[] = $track;
- }
- } }
- }
-
- class CDSearchByBandIterator 實作迭代器{
-
- private $_CDs = array();
- private $_valid = FALSE;
-
- public function __struct($struct) $db = mysql_connect("localhost", "root", "root");
- mysql_select_db("test");
-
- $sql = "選擇CD.id, CD.band, CD.title 、tracks.tracknum、tracks.title as tracktitle ";
- $sql .= "從CD 左連接CD.id = Tracks.cid 上的曲目";
- $sql .= "其中band = ' 」。 mysql_real_escape_string($bandName) 。 ;
- $cd = NULL;
-
- while ($result = mysql_fetch_array($results)) {
- if ($result["id"] !== $cdID) {
- if ( !is_null($cd) )) {
- $this->_CDs[] = $cd;
- }
-
- $cdID = $result['id'];
- $cd = 新CD($result ['band'], $result['title']);
- }
-
- $cd->addTrack($result['tracktitle']);
- }
- }
-
- $this->_CDs[] = $cd;
- }
-
- public function next() {
- $this->_valid = (next($this->_CDs ) FALSE : TRUE;
- }
-
- public function rewind() {
- $this->_valid = (reset($this->_CDs) === FALSE) FALSE : TRUE;
- }
-
- public function valid() {
- return $this->_valid;
- }
-
- public function current() {
- return current($this-> _CDs);
- }
-
- public function key() {
- return key($this->_CDs);
- }
- }
-
- $queryItem = " Never Again";
-
- $cds = new CDSearchByBandIterator($queryItem);
-
- print "
找到以下CD" ;
- print "
Band |
Ttile |
Num Tracks |
";- foreach ($ cds as $cd) {
- print "
{$cd->band} |
{$cd ->標題} |
";- 列印統計($cd-> trackList)。定位檔Design/Iterator.class.php */
-
-
- 複製程式碼
/* 定位檔案Design /Mediator.class.php */
複製程式碼
- /*
- SQLyog 企業版- MySQL GUI v8.14
- MySQL - 5.1.52-community : 資料庫- 測驗
- ******* * ************************************************* ********* ************
- */
-
- /*!40101 設定名稱utf8 */;
-
- /* !40101 SET SQL_MODE=''*/ ;
-
- /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
- /*!40014 CHECKS =0 */;
- / *!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
- /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES=/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES 🎜>/*表`的表結構cd` */
-
- 如果存在`cd`,則刪除表;
-
- 建立表`cd` (
- `id` int(8 ) NOT NULL AUTO_INCRMENT,
- `band` varchar(500) COLLATE latin1_bin NOT NULL DEFAULT '',
- `title` varchar(500) COLLATE latin1_bin NOT NULLULL> `title` varchar(500) COLLATE latin1_bin NOT NULLULLFAULT ” ) DEFAULT NULL,
- `amount` int (8) DEFAULT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCRMENT=2 DEFAULT CHARSET=latin1 >/*表`cd` 的資料* /
-
- 插入`cd`(`id`,`band`,`title`,`bought`,`amount`) 值(1,'Never Again' ,'Waster of a Rib',1 ,98);
-
- /*表`tracks` 的表結構*/
-
- DROP TABLE IF EXISTS `tracks`;
-
- CREATE TABLE `tracks` (
- `cid` int(8) DEFAULT NULL,
- `tracknum` int(8) DEFAULT NULL,
- `title` varchar(500) COLLATE latin1_bin NN N NULL* 🎜>) ENGINE=InnoDB DEFAULT CHARSET= latin1 COLLATE=latin1_bin;
-
- /*表格`tracks` 的資料*/
-
- 插入`tracks`(`cid`,`racknum`,`,`racknum`,`,`racknum. title`) 值(1, 3,'這代表什麼'),(1,3,'Brr'),(1,3,'再見');
-
- /*!40101 SET SQL_MODE= @OLD_SQL_MODE */;
- /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
- /*!40014 SET UNIQUE_CHECKS=@OLD_UNI>/*!40014 SET UNIQUE_CHECKS=@OLD_UNIm.
-
-
-
- 複製程式碼
-
-
-
|
|