适用性
对对象加以【控制】
和适配器的区别:适配器是连接两个接口(【改变】了接口)
和装饰器的区别:装饰器是对现有的对象包装(【功能扩展】
代码示例
/**
* 鞋接口
*/
interface ShoesInterface
{
public function product();
}
/**
* 滑板鞋实体
*/
class ShoesSkateboard implements ShoesInterface
{
public function product()
{
echo "生产一滑板鞋";
}
}
/**
* 运动鞋实体
*/
class ShoesSport implements ShoesInterface
{
public function product()
{
echo "生产一双球鞋";
}
}
/**
* 代理工厂
*/
class Proxy
{
/**
* 产品生产线对象
*/
private $_shoes;
/**
* 产品生产线类型
*/
private $_shoesType;
/**
* 构造函数.
*/
public function __construct($shoesType)
{
$this->_shoesType = $shoesType;
}
/**
* 生产.
*/
public function product()
{
switch ($this->_shoesType) {
case 'sport':
echo "我可以偷点工";
$this->_shoes = new ShoesSport();
break;
case 'skateboard':
echo "我可以减点料";
$this->_shoes = new ShoesSkateboard();
break;
default:
throw new Exception("shoes type is not available", 404);
break;
}
$this->_shoes->product();
}
}
try {
echo "未加代理之前:\n";
// 生产运动鞋
$shoesSport = new ShoesSport();
$shoesSport->product();
echo "\n--------------------\n";
//-----------------------------------
echo "加代理:\n";
$proxy = new Proxy('sport');
$proxy->product();
} catch (\Exception $e) {
echo $e->getMessage();
}