PHP设计模式之代理模式
代理模式定义
为其他对象提供一种代理,以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介作用。
代理模式使用场景
- 职责清晰,委托类只需关注自身功能实现,不需要非自身职责;
- 代理对象可以在客户端和目标对象之间起到中介作用,保护目标对象;
- 可拓展性更强。
缺点:
- 代理类的增加,会使系统文件增加,增加复杂度;
- 增加一层代理类,性能会有所损耗;
代理模式代码实现
ByHouseInterface.php<?php
namespace App\Structural\Proxy;
interface ByHouseInterface
{
public function byHouse();
}
[TomByHouse.php](https://github.com/echoou2020/pattern/blob/master/App/Structural/Proxy/TomByHouse.php)
```php
<?php
namespace App\Structural\Proxy;
class TomByHouse implements ByHouseInterface
{
public function byHouse()
{
echo "tom by a house \r\n";
}
}
<?php
namespace App\Structural\Proxy;
class ByHousePorxy implements ByHouseInterface
{
protected $customer;
public function __construct(ByHouseInterface $customer)
{
$this->customer = $customer;
}
public function byHouse()
{
echo "by house before \r\n";
$this->customer->byHouse();
echo "by house after \r\n";
return 1;
}
}
<?php
class ProxyTest extends \PHPUnit\Framework\TestCase
{
public function testByHouse()
{
$proxy = new \App\Structural\Proxy\ByHousePorxy(new \App\Structural\Proxy\TomByHouse());
$this->assertEquals(1, $proxy->byHouse());
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接