php之大话装饰模式

这里的构造函数居然这样写。

<meta charset="utf-8">
<?php

function Person($data = array())
{
	{/* __construct */
		static $i = 0;
		++$i;
		extract(array_merge(array('name' => '未命名') /* 默认值 */, $data));
	}
	
	return array(
		'Show' => function() use($name, $i)
		{
			echo "装扮的{$name}, 第{$i}个Person对象";
		}
	);
}

function Finery($component)
{
	return array(
		'Show' => function() use($component)
		{
			$component['Show']();
		}
	);
}

function TShirts($component)
{
	$f_parent = Finery($component);
	return array(
		'Show' => function() use($f_parent)
		{
			echo '大T恤 ';
			$f_parent['Show']();
		}
	);
}

function BigTrouser($component)
{
	$f_parent = Finery($component);
	return array(
		'Show' => function() use($f_parent)
		{
			echo '垮裤 ';
			$f_parent['Show']();
		}
	);
}

$p = Person(array('name' => '额'));
$p = Person();
$bt = BigTrouser($p);
$ts = TShirts($bt);

$ts['Show']();
	
/* f_finery.php */

面向对象


<meta charset="utf-8">
<?php

class Person
{
	private $name;
	function __construct($name = '')
	{
		if($name !== '') $this->name = $name;
	}

	public function Show()
	{
		echo '装扮的' . $this->name;
	}
}

class Finery extends Person
{
	protected $component;

	//打扮
	public function Decorate(Person $component_)
	{
		$this->component = $component_;
	}

	public function Show()
	{
		if ($this->component != null)
		{
			$this->component->Show();
		}
	}
}

class TShirts extends Finery
{
	public function Show()
	{
		echo '大T恤 ';
		parent::Show();
	}
}

class BigTrouser extends Finery
{
	public function Show()
	{
		echo '垮裤 ';
		parent::Show();
	}
}

$p = new Person('额');
$bt = new BigTrouser();
$ts = new TShirts();

$bt->Decorate($p);
$ts->Decorate($bt);
$ts->Show();
	
/* c_finery.php */
	
  

实际上,用oo或者仿oo,还是复杂了些,最简单的说明就是。

$fn = function() {
    echo ' body ';
};

$fn = function() use($fn) {
    echo 'head ';
    $fn();
    echo ' footer';
};

$fn();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值