zoukankan      html  css  js  c++  java
  • 让面向对象编程更加灵活的的模式-----装饰模式

    引言

    组合模式帮组我们聚合组件,装饰模式则使用类似节后来帮组我们改变具体组件的功能

    问题

    将所有功能简历在集成体系上会导致系统中的类“爆炸式”增多,当你尝试对集成书上不同的分支做想死的修改是,代码可能会产生重复

     uml图

    代码实现

    <?php
    /*
    decoration.php
    装饰模式
    */
    
    class Requesthelper{}
    
    //抽象基类
    abstract class ProcessRequest{
        abstract function process(Requesthelper $req);
    }
    
    //具体的组件
    class MainProcess extends ProcessRequest{
        function process(Requesthelper $req){
            print __CLASS__.": doing something useful with request<br>";
        }
    }
    
    //抽象装饰类
    abstract class DecorateProcess extends ProcessRequest{//继承
        protected $processrequest;
        function __construct(ProcessRequest $pr){//组合
            $this->processrequest = $pr;
        }
    }
    
    //日志装饰类
    class LogRequest extends DecorateProcess{
        function process(Requesthelper $req){
            print __CLASS__.": logging request<br>";
            $this->processrequest->process($req);//委托
        }
    }
    
    //认证装饰类
    class AuthenticateRequest extends DecorateProcess{
        function process(Requesthelper $req){
            print __CLASS__.": authenticating request<br>";
            $this->processrequest->process($req);
        }
    }
    
    //认证装饰类
    class StructreRequest extends DecorateProcess{
        function process(Requesthelper $req){
            print __CLASS__.": structring request<br>";
            $this->processrequest->process($req);
        }
    }
    
    //client
    $process = new AuthenticateRequest(new StructreRequest(new LogRequest(new MainProcess())));
    $process ->process(new Requesthelper());
    ?>

    效果

    组合和继承通常都是同时使用的,因此logrequest是继承自processrequest,但是却保险为对另外一个processrequest对象的封装

    因为修饰对象作为子对象的包装,所以保持基类中的方法尽可能少是很重要的

  • 相关阅读:
    同一部电脑配两个git账号
    在span中,让里面的span垂直居中用这个
    三张图搞懂JavaScript的原型对象与原型链
    vue2.0 生命周期
    js中__proto__和prototype的区别和关系?
    【转】css 包含块
    【转】BFC(block formating context)块级格式化上下文
    javascript中函数的5个高级技巧
    toString() 和 valueOf()
    桌面图标列表排列小工具
  • 原文地址:https://www.cnblogs.com/rcjtom/p/6065986.html
Copyright © 2011-2022 走看看