0

0

代码均来源于《PHP设计模式》一书

PHP中文网

PHP中文网

发布时间:2016-05-25 17:12:34

|

1264人浏览过

|

来源于php中文网

原创

代码均来源于《php设计模式》一书 

1. [文件]     Decorator.class.php 

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("What It Means", "Brr", "Goodbye");

$myCD = new CD();
foreach ($tracksFroExternalSource as $track) {
	$myCD->addTrack($track);
}

print "The CD contains:{$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";

/* End of Decorator.class.php */
/* Location the file Design/Decorator.class.php */

              

2. [文件]     Delegate.class.php 

_songs = array();
	}
	
	public function addSong($location, $title) {
		$song = array("location" => $location, "title" => $title);
		$this->_songs[] = $song;
	}
	
	public function getM3U() {
		$m3u = "#EXTM3U\n\n";
		
		foreach ($this->_songs as $song) {
			$m3u .= "#EXTINF: -1, {$song['title']}\n";
			$m3u .= "{$song['location']}\n";
		}
		
		return $m3u;
	}
	
	public function getPLS() {
		$pls = "[playlist]]\nNumberOfEntries = ". count($this->_songs) . "\n\n";
		
		foreach ($this->_songs as $songCount => $song) {
			$counter = $songCount + 1;
			$pls .= "File{$counter} = {$song['location']}\n";
			$pls .= "Title{$counter} = {$song['title']}\n";
			$pls .= "LengthP{$counter} = -1 \n\n";
		}
		
		return $pls;
	}
}

$playlist = new Playlist();

$playlist->addSong("/home/aaron/music/brr.mp3", "Brr");
$playlist->addSong("/home/aaron/music/goodbye.mp3", "Goodbye");

$externalRetrievedType = "pls";

if ($externalRetrievedType == "pls") {
	$playlistContent =  $playlist->getPLS();
} else {
	$playlistContent =  $playlist->getM3U();
}

echo $playlistContent;

//委托模式实现 
class newPlaylist {

	private $_songs;
	private $_tyepObject;

	public function __construct($type) {
		$this->_songs = array();
		$object = "{$type}Playlist";
		$this->_tyepObject = new $object;
	}	
	
	public function addSong($location, $title) {
		$song = array("location" => $location, "title" => $title);
		$this->_songs[] = $song;
	}
	
	public function getPlaylist() {
		$playlist = $this->_tyepObject->getPlaylist($this->_songs);
		return $playlist;
	}
}

class m3uPlaylist {
	public function getPlaylist($songs) {
		$m3u = "#EXTM3U\n\n";
		
		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 = ". count($songs) . "\n\n";
		
		foreach ($songs as $songCount => $song) {
			$counter = $songCount + 1;
			$pls .= "File{$counter} = {$song['location']}\n";
			$pls .= "Title{$counter} = {$song['title']}\n";
			$pls .= "LengthP{$counter} = -1 \n\n";
		}
		
		return $pls;
	}
}

$externalRetrievedType = "pls";
$playlist = new newPlaylist($externalRetrievedType);

$playlist->addSong("/home/aaron/music/brr.mp3", "Brr");
$playlist->addSong("/home/aaron/music/goodbye.mp3", "Goodbye");

$playlistContent = $playlist->getPlaylist();

echo $playlistContent;

/* End of Delegate.class.php */
/* Location the file Design/Delegate.class.php */

               

3. [文件]     Facade.class.php

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 makeXMLCall(CD $cd) {
		CDUpperCase::makeString($cd, "title");
		CDUpperCase::makeString($cd, "band");
		CDUpperCase::makeArray($cd, "tracks");
		
		$xml = CDMakeXML::create($cd);
		
		return $xml;
	}
}

$tracksFromExternalSource = array("What It Means", "Brr", "Goodbye");
$band  = "Never Again";
$title = "Waster of a Rib";

$cd = new CD($tracksFromExternalSource, $band, $title);

$xml = WebServiceFacade::makeXMLCall($cd);

echo $xml;


/* End of Facade.class.php */
/* Location the file Design/Facade.class.php */

4. [文件]     Factory.class.php

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   = CDFactory::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 */

  

5. [文件]     Interpreter.class.php

_username = $username;
	}
	
	public function getProfilePage() {
		$profile  = "

I like Never Again !

"; $profile .= "I love all of their songs. My favorite CD:
"; $profile .= "{{myCD.getTitle}}!!"; return $profile; } } class userCD { 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 setUser(User $user) { $this->_user = $user; } public function getInterpreted() { $profile = $this->_user->getProfilePage(); if (preg_match_all('/\{\{myCD\.(.*?)\}\}/', $profile, $triggers, PREG_SET_ORDER)) { $replacements = array(); foreach ($triggers as $trigger) { $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 */

6. [文件]     Iterator.class.php 

band  = $band;
		$this->title = $title;
	}
	
	public function addTrack($track) {
		$this->trackList[] = $track;
	}
}

class CDSearchByBandIterator implements Iterator {
	
	private $_CDs   = array();
	private $_valid = FALSE;
	
	public function __construct($bandName) {
		$db = mysql_connect("localhost", "root", "root");
		mysql_select_db("test");
		
		$sql  = "select CD.id, CD.band, CD.title, tracks.tracknum, tracks.title as tracktitle ";
		$sql .= "from CD left join tracks on CD.id = tracks.cid ";
		$sql .= "where band = '" . mysql_real_escape_string($bandName) . "' ";
		$sql .= "order by tracks.tracknum";
		
		$results = mysql_query($sql);

		$cdID = 0;
		$cd   = NULL;
		
		while ($result = mysql_fetch_array($results)) {
			if ($result["id"] !== $cdID) {
				if ( ! is_null($cd)) {
					$this->_CDs[] = $cd;
				}
				
				$cdID = $result['id'];
				$cd   = new CD($result['band'], $result['title']);
			}
			
			$cd->addTrack($result['tracktitle']);
		}
		
		$this->_CDs[] = $cd;
	}
	
	public function next() {
		$this->_valid = (next($this->_CDs) === FALSE) ? 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 "

Found the Following CDs

"; print ""; foreach ($cds as $cd) { print ""; } print "
BandTtileNum Tracks
{$cd->band}{$cd->title}"; print count($cd->trackList). "
"; /* End of Iterator.class.php */ /* Location the file Design/Iterator.class.php */

          

Ke361开源淘宝客系统
Ke361开源淘宝客系统

Ke361是一个开源的淘宝客系统,基于最新的ThinkPHP3.2版本开发,提供更方便、更安全的WEB应用开发体验,采用了全新的架构设计和命名空间机制, 融合了模块化、驱动化和插件化的设计理念于一体,以帮助想做淘宝客而技术水平不高的朋友。突破了传统淘宝客程序对自动采集商品收费的模式,该程序的自动 采集模块对于所有人开放,代码不加密,方便大家修改。集成淘点金组件,自动转换淘宝链接为淘宝客推广链接。K

下载

立即学习PHP免费学习笔记(深入)”;

7. [文件]     Mediator.class.php 

_mediator = $mediator;
	}
	
	public function save() {
		//具体实现待定
		var_dump($this);
	}
	
	public function changeBandName($bandname) {
		if ( ! is_null($this->_mediator)) {
			$this->_mediator->change($this, array("band" => $bandname));
		}
		$this->band = $bandname;
		$this->save();
	}
}

//MP3Archive类
class MP3Archive {
	
	protected $_mediator;
	
	public function __construct(MusicContainerMediator $mediator = NULL) {
		$this->_mediator = $mediator;
	}
	
	public function save() {
		//具体实现待定
		var_dump($this);
	}
	
	public function changeBandName($bandname) {
		if ( ! is_null($this->_mediator)) {
			$this->_mediator->change($this, array("band" => $bandname));
		}
		$this->band = $bandname;
		$this->save();
	}
}

//中介者类
class MusicContainerMediator {
	
	protected $_containers = array();
	
	public function __construct() {
		$this->_containers[] = "CD";
		$this->_containers[] = "MP3Archive";
	}
	
	public function change($originalObject, $newValue) {
		$title = $originalObject->title;
		$band  = $originalObject->band;
		
		foreach ($this->_containers as $container) {
			if ( ! ($originalObject instanceof $container)) {
				$object = new $container;
				$object->title = $title;
				$object->band  = $band;
				
				foreach ($newValue as $key => $val) {
					$object->$key = $val;
				}
				
				$object->save();
			}
		}
	}
}

//测试实例
$titleFromDB = "Waste of a Rib";
$bandFromDB  = "Never Again";

$mediator = new MusicContainerMediator();

$cd = new CD($mediator);
$cd->title = $titleFromDB;
$cd->band  = $bandFromDB;

$cd->changeBandName("Maybe Once More");

/* End of Mediator.class.php */
/* Location the file Design/Mediator.class.php */

8. [文件]     test.sql 

/*
SQLyog 企业版 - MySQL GUI v8.14 
MySQL - 5.1.52-community : Database - test
*********************************************************************
*/

/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
/*Table structure for table `cd` */

DROP TABLE IF EXISTS `cd`;

CREATE TABLE `cd` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `band` varchar(500) COLLATE latin1_bin NOT NULL DEFAULT '',
  `title` varchar(500) COLLATE latin1_bin NOT NULL DEFAULT '',
  `bought` int(8) DEFAULT NULL,
  `amount` int(8) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1 COLLATE=latin1_bin;

/*Data for the table `cd` */

insert  into `cd`(`id`,`band`,`title`,`bought`,`amount`) values (1,'Never Again','Waster of a Rib',1,98);

/*Table structure for table `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 NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_bin;

/*Data for the table `tracks` */

insert  into `tracks`(`cid`,`tracknum`,`title`) values (1,3,'What It Means'),(1,3,'Brr'),(1,3,'Goodbye');

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

                               

                   

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

php

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
php与html混编教程大全
php与html混编教程大全

本专题整合了php和html混编相关教程,阅读专题下面的文章了解更多详细内容。

6

2026.01.13

PHP 高性能
PHP 高性能

本专题整合了PHP高性能相关教程大全,阅读专题下面的文章了解更多详细内容。

6

2026.01.13

MySQL数据库报错常见问题及解决方法大全
MySQL数据库报错常见问题及解决方法大全

本专题整合了MySQL数据库报错常见问题及解决方法,阅读专题下面的文章了解更多详细内容。

6

2026.01.13

PHP 文件上传
PHP 文件上传

本专题整合了PHP实现文件上传相关教程,阅读专题下面的文章了解更多详细内容。

5

2026.01.13

PHP缓存策略教程大全
PHP缓存策略教程大全

本专题整合了PHP缓存相关教程,阅读专题下面的文章了解更多详细内容。

3

2026.01.13

jQuery 正则表达式相关教程
jQuery 正则表达式相关教程

本专题整合了jQuery正则表达式相关教程大全,阅读专题下面的文章了解更多详细内容。

1

2026.01.13

交互式图表和动态图表教程汇总
交互式图表和动态图表教程汇总

本专题整合了交互式图表和动态图表的相关内容,阅读专题下面的文章了解更多详细内容。

15

2026.01.13

nginx配置文件详细教程
nginx配置文件详细教程

本专题整合了nginx配置文件相关教程详细汇总,阅读专题下面的文章了解更多详细内容。

4

2026.01.13

nginx部署php项目教程汇总
nginx部署php项目教程汇总

本专题整合了nginx部署php项目教程汇总,阅读专题下面的文章了解更多详细内容。

5

2026.01.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
PHP课程
PHP课程

共137课时 | 8.6万人学习

JavaScript ES5基础线上课程教学
JavaScript ES5基础线上课程教学

共6课时 | 6.9万人学习

PHP新手语法线上课程教学
PHP新手语法线上课程教学

共13课时 | 0.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号