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

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

  • 相关阅读:
    面向对象的静态属性和静态方法
    面向对象魔术方法及类的自动加载
    面向对象
    mysql cmd 创表查表练习
    创建表 查询表以及添加数据
    windows cmd命令
    4.20 mysq数据库 创建表
    cmd控制数据库初步了解
    Jquery初步了解
    故宫博物院项目 JS功能整理
  • 原文地址:https://www.cnblogs.com/rcjtom/p/6065986.html
Copyright © 2011-2022 走看看