<?php
/**
* 职责清晰,真实的角色就是实现实际的业务逻辑,不用关心其他非本职责的事务,通过后期的代理完成一件事务,附带的结果就是编程简洁清晰。
高扩展性。
智能化。
*
*
*/
//普通代理:客户端只需要获取代理的对象,即可完成操作,无需知道真实角色是什么。
/*
interface IUser {
public function login();
public function operate();
public function logout();
}
final class Admin implements IUser {
private $_name;
public function __construct($name) {
$this->_name = $name;
}
public function login() {
echo 'welcome ' . $this->_name . ' back!' . PHP_EOL;
}
public function operate() {
echo $this->_name . ' start to operate!' . PHP_EOL;
}
public function logout() {
echo $this->_name . ' logout, remember to come back! Bye!' . PHP_EOL;
}
}
final class UserProxy implements IUser {
private $_user = null;
public function __construct(IUser $user) {
$this->_user = $user;
}
public function login() {
$this->_user->login();
}
public function operate() {
$this->_user->operate();
}
public function logout() {
$this->_user->logout();
}
}
$user = new Admin('pipi');
$proxy = new UserProxy($user);
$proxy->login();
$proxy->operate();
$proxy->logout();
*/
//强制代理:必须通过真实角色找到代理角色,否则不允许访问。
interface IUser {
public function login();
public function operate();
public function logout();
public function getProxy();
}
final class Merchant implements IUser {
private $_name;
private $_proxy = null;
public function __construct($name) {
$this->_name = $name;
}
public function login() {
echo (is_null($this->_proxy) ? 'please get your proxy!' : 'welcome ' . $this->_name . ' back!') . PHP_EOL;
}
public function operate() {
echo (is_null($this->_proxy) ? 'please get your proxy!' : $this->_name . ' start to operate') . PHP_EOL;
}
public function logout() {
echo (is_null($this->_proxy) ? 'please get your proxy!' : $this->_name . ' logout, remember to come back!') . PHP_EOL;
}
public function getProxy() {
$this->_proxy = new EnforceProxy($this);
return $this->_proxy;
}
}
final class EnforceProxy implements IUser {
private $_user = null;
public function __construct(IUser $user) {
$this->_user = $user;
}
public function login() {
$this->_user->login();
}
public function operate() {
$this->_user->operate();
}
public function logout() {
$this->_user->logout();
}
public function getProxy() {
return $this;
}
}
// 无法调用,由于强制代理,必须先获取属于该用户的代理
// $user = new Merchant('John');
// $proxy = new EnforceProxy($user);
// $proxy->login();
// $proxy->operate();
// $proxy->logout();
$user = new Merchant('JACK');
$proxy = $user->getProxy();
$proxy->login();
$proxy->operate();
$proxy->logout();
/*
一个类可以实现多个接口,完成不同任务的整合。也就是说代理类不仅仅可以实现主题接口,也可以实现其他接口完成不同的任务,而且代理的目的是在目标对象方法的基础上作增强,这种增强的本质通常就是对目标对象的方法进行拦截和过滤。
* */
网友评论