本文的示例代码参考decorator_proxy
目录
Decorator
示例
vim decorator.php
<?php
interface Middleware {
public function handle();
}
class Controller implements Middleware {
public function handle() {
echo "Controller逻辑\n";
}
}
class EncryptCookies implements Middleware {
private $middleware;
function __construct($middleware) {
$this->middleware = $middleware;
}
public function handle() {
echo "解密输入请求cookie\n";
$this->middleware->handle();
echo "加密输出响应cookie\n";
}
}
class StartSession implements Middleware {
private $middleware;
function __construct($middleware) {
$this->middleware = $middleware;
}
public function handle() {
echo "开启session获取数据\n";
$this->middleware->handle();
echo "保存数据关闭session\n";
}
}
function request() {
$pipeline = new Controller();
$pipeline = new StartSession($pipeline);
$pipeline = new EncryptCookies($pipeline);
$pipeline->handle();
}
request();
php decorator.php
解密输入请求cookie
开启session获取数据
Controller逻辑
保存数据关闭session
加密输出响应cookie
特点: 面向接口
特点: 嵌套扩展
Proxy
示例
vim proxy.php
<?php
interface Printable {
public function print();
}
class Printer implements Printable {
private $state = "idle";
public function print() {
$this->state = "working";
echo "打印机开始打印\n";
}
public function state() {
return $this->state;
}
}
class PrinterProxy implements Printable {
private $printer;
public function print() {
if (! $this->printer) {
$this->printer = new Printer();
}
$state = $this->printer->state();
if ($state === "idle") {
$this->printer->print();
} else if ($state === "working") {
echo "打印机正在打印\n";
}
}
}
function main() {
$printerProxy = new PrinterProxy();
$printerProxy->print();
$printerProxy->print();
}
main();
php proxy.php
打印机开始打印
打印机正在打印
特点: 面向接口
特点: 控制优化
Decorator vs Proxy
结构类似的Decorator与Proxy 最大的不同是在于目的: Decorator便于扩展功能 而Proxy便于控制优化
网友评论