设计模式 之 Decorator vs Proxy

本文的示例代码参考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便于控制优化

参考

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,831评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,288评论 19 139
  • 🎉 对设计模式的极简说明!🎉 这个话题可以轻易让任何人糊涂。现在我尝试通过用 最简单 的方式说明它们,来让你(和我...
    月球人simon阅读 1,137评论 1 2
  • 今天的晴阳, 略微显现出灵魂的干燥。 没有雪, 却苍白了脸色和月光。 仅一个夜晚, 隔了时间, 偷换了心跳的节奏。...
    草木萦心阅读 461评论 3 4
  • 心情不好,头痛难忍,觉着自己太low了,说话不到位,没有把对方说倒,说的明白,心里一阵懊恼,烦躁。想把工作辞掉自己...
    蓝海心理阅读 239评论 0 0