螃蟹学PHP设计模式之装饰器模式

4.装饰器模式

趁着还没下班,再来一发,学习一下装饰器模式。螃蟹通过之前的学习发现设计模式还是很有意思的,而且都是前辈总结的经验,不能不好好学习。对于装饰器模式很好理解,就好像你通过奋斗终于买了一套房,但是房子很暗,怎么办,装上灯泡就行了。是不是很好理解,装饰器模式就是原对象的方法或属性不能很好的适应我们的业务需求时,就需要用装饰器转换一下再输出,像比较简单的时间戳转日期字符串可以不需要,但是复杂一点的就最好用装饰器模式了。

参考项目模块:微博发布系统

虽然螃蟹没写过微博发布程序,但是相信很多人用过微博都会发现每条微博都有时间显示,一般都是几秒几分钟前,几小时几天都有,这个微博发布的时间一般都是使用时间戳来存储的,所以显示时要做转换,这里装饰器模式就派上用场了。

 微博对象类:Weibo.class.php

<?php 

class Weibo{
	protected $_content = null;
	protected $_author = null;
	protected $_created = 0;
	
	function __construct($weibo){
		$this->_author = $weibo['author'];
		$this->_content = $weibo['content'];
		$this->_created = $weibo['created'];
	}
	/**
	 * @return the $_content
	 */
	public function getContent() {
		return $this->_content;
	}

	/**
	 * @return the $_author
	 */
	public function getAuthor() {
		return $this->_author;
	}

	/**
	 * @return the $_created
	 */
	public function getCreated() {
		return $this->_created;
	}

	/**
	 * @param NULL $_content
	 */
	public function setContent($_content) {
		$this->_content = $_content;
	}

	/**
	 * @param NULL $_author
	 */
	public function setAuthor($_author) {
		$this->_author = $_author;
	}

	/**
	 * @param number $_created
	 */
	public function setCreated($_created) {
		$this->_created = $_created;
	}

		
}
?>

微博装饰器类:WeiboDecorator.class.php

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

class WeiboDecorator{
	protected $_weibo = null;
	
	function __construct(Weibo $weibo){
		$this->_weibo = $weibo;
	}
	
	public function getTimeInterval(){
		if(time() - $this->_weibo->getCreated() <60){
			$this->_weibo->setCreated((time() - $this->_weibo->getCreated()).'秒前');
		}
		if((time() - $this->_weibo->getCreated())/60<60){
			$this->_weibo->setCreated(intval((time() - $this->_weibo->getCreated())/60).'分钟前');				
		}
	}
}
?>

最后编辑测试类:TestDecorator.php

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

//模拟微博数据
$weibo1 = array('author'=>'螃蟹','content'=>'今天下班晚了!','created'=>(time()-32));
//模拟微博数据
$weibo2 = array('author'=>'螃蟹','content'=>'不要这样好吗','created'=>(time()-130));

//实例化微博对象
$weiboobj1 = new Weibo($weibo1);
$weiboobj2 = new Weibo($weibo2);

//装饰器处理
$weibodec1 = new WeiboDecorator($weiboobj1);
$weibodec2 = new WeiboDecorator($weiboobj2);
$weibodec1->getTimeInterval();
$weibodec2->getTimeInterval();

//输出结果
print_r($weiboobj1);
print_r($weiboobj2);
?>

看看输出结果

Weibo Object ( [_content:protected] => 今天下班晚了! [_author:protected] => 螃蟹 [_created:protected] => 32秒前 ) Weibo Object ( [_content:protected] => 不要这样好吗 [_author:protected] => 螃蟹 [_created:protected] => 2分钟前 )

好测试完成了,螃蟹也要下班了...明天继续

你可能感兴趣的:(设计模式,PHP,装饰器模式)