螃蟹学PHP设计模式之委托模式

5.委托模式

大半夜的时候,估计是单身码农最活跃的敲代码的时候吧。螃蟹今天已经学了两种设计模式了,一种是数据访问对象模式,另一种是装饰器模式,前一种还是很好理解,因为用的多,后一种装饰器模式则是获取对象后的修饰处理,螃蟹还是搞清楚了。现在反正也是睡不着,不如再搞定一个委托模式。螃蟹就简单一点理解了,螃蟹现在也就一年就毕业了,面临找工作了,但是公司那么多,怎么办了,螃蟹就把简历放到招聘网站上,委托网站来投递给公司,这样螃蟹就不用一个一个公司去投简历了。委托模式的设计也是出于这样的考虑,可能原对象要增加很多功能,直接在原对象中添加会显得很庞大,而直接在业务代码中实现,就会出现繁多的判断语句,把新增的功能单独写成统一格式的类,再使用委托者来收集和处理业务的需求,则可以很方便的实现业务的变动。

参考项目模块:评论系统

螃蟹之前做项目遇到过这样的评论系统,不仅文章可以评论,而且商品可以评论,而且后面开发说不定还有新的东西可以评论,虽然当时用判断语句解决了这个问题,目前看到是不够高明的,螃蟹一直遵循学以致用的原则,现在就尝试用委托模式重新设计一下看看。

这个是原先设计的评论类:Comments.class.php

<?php 
class Comments{
	protected $_username = null;
	protected $_conetent = null;
	protected $_type = null;
	
	//添加文章评论
	public function addEssay($comments){
		$this->_username = $comments['username'];
		$this->_conetent = $comments['content'];
		$this->_type = 'ESSAY';
	}
	//添加商品评论
	public function addProduct($comments){
		$this->_username = $comments['username'];
		$this->_conetent = $comments['content'];
		$this->_type = 'PRODUCT';
	}
	
	//获取评论
	public function getComments(){
		$comments = array();
		$comments['username'] = $this->_username;
		$comments['content'] = $this->_conetent;
		$comments['type'] = $this->_type;
		return $comments;
	}
}
?>

显然如果要再增加评论类目就必须要再添加方法,要取出不同评论还要添加方法,确实很累赘,这样我们设计一个委托类来处理全部评论的请求:NewComments.class.php

<?php 
require('ESSAYComments.class.php');
require('PRODUCTComments.class.php');

class NewComments{
	protected $_comments;
	protected $_commentsobj;
	protected $_type;

	function __construct($type){
		$this->_comments = array();
		$object = $type.'Comments';
		$this->_commentsobj = new $object;
		$this->_type = $type;
	}
	
	//添加评论
	public function addComments($username,$content){
		$comments = array('username'=>$username,'conetent'=>$content,'type'=>$this->_type);
		$this->_comments[] = $comments;
	}
	
	//获取评论
	public function getComments(){
		$comments = $this->_commentsobj->getComments($this->_comments);
		return $comments;
	}
}

?>

这里就可以随心所欲的添加想要的评论类型了,只需要定义getComments方法即可:

ESSAYComments.class.php

<?php 
class PRODUCTComments{
	public function getComments($comments){
		echo '<br>商品评论:<br>';
		print_r($comments);
	}
}
?>

PRODUCTComments.class.php

<?php 
class ESSAYComments{
	public function getComments($comments){
		echo '<br>文章评论:<br>';
		print_r($comments);
	}
}
?>

好时间不早了,还是编写测试类测试一下:TestDelegate.php

<?php 
require('NewComments.class.php');

//模拟评论数据
$username = '螃蟹';
$content1 = '这篇文章写的不错';
$content2 = '岛国充气娃娃';
$type1 = 'ESSAY';
$type2 = 'PRODUCT';
//处理评论
$commentsobj = new NewComments($type1);
$commentsobj->addComments($username, $content1);
$commentsobj->getComments();

$commentsobj = new NewComments($type2);
$commentsobj->addComments($username, $content2);
$commentsobj->getComments();

?>

看看测试结果:

文章评论:
Array ( [0] => Array ( [username] => 螃蟹 [conetent] => 这篇文章写的不错 [type] => ESSAY ) ) 
商品评论:
Array ( [0] => Array ( [username] => 螃蟹 [conetent] => 岛国充气娃娃 [type] => PRODUCT ) )

好终于可以睡觉了,躺在床板上写代码,螃蟹的脖子都酸了,可以合上电脑了,那就晚安了。

你可能感兴趣的:(设计模式,PHP,委托模式)