PHP设计模式-代理 发表于 2017-03-28 | 分类于 PHP | 评论数: | 阅读次数: 本文字数: 1.6k | 阅读时长 ≈ 1 分钟 适用性 对对象加以【控制】 和适配器的区别:适配器是连接两个接口(【改变】了接口) 和装饰器的区别:装饰器是对现有的对象包装(【功能扩展】 代码示例123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293/** * 鞋接口 */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();}