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对象的封装

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

  • 相关阅读:
    Angularjs 设置全局变量的3种方法
    prevent to do sth 与 prevent sb (from) doing 用法
    软件测试技术对程序员的重要性
    Javascript中setTimeout()以及clearTimeout( )的使用
    Javascript异步编程的常用方法
    软件设计原则总结
    为sublime Text3 安装插件JS Format
    javascript中 if(变量)和if(变量==true)的区别
    Ping 命令
    ipconfig
  • 原文地址:https://www.cnblogs.com/rcjtom/p/6065986.html
Copyright © 2011-2022 走看看