zoukankan      html  css  js  c++  java
  • 设计模式-装饰者

    之前的模板方法虽然解决了代码多余的问题,但是缺点也是显而易见的,我只能被迫接收所有继承的,所以有了这第二个模式 装饰者模式

    还是之前的业务逻辑,现在我可以这么写

    public interface Command(){
    
    public void excute();
    
    }

    //一个类来执行输出日志

    public class Printlog implements Command(){
    
    Command cmd;
    
    public Printlog(Command cmd){
    
    this.cmd=cmd;
    
    }
    
    @Override
    
    public void excute(){
    
    //日志
    
    ....
    
    this.cmd.excute();
    
    }
    
    }

    //一个类用来性能统计

    public class Performance implements Command(){
    
    Command cmd;
    
    public Performance(Command cmd){
    
    this.cmd=cmd;
    
    }
    
    @Override
    
    public void excute(){
    
    //性能统计
    
    .....
    
    this.cmd.excute();
    
    }
    
    }
    public PlaceOrderCommand implements Command(){
    
    @Override
    
    public void excete(){
    
    //下单操作
    
    }
    
    }
    psvm{
    
    //现在想下单的时候进行性能统计和打印日志
    
    //理一下顺序 创建Printlog 需要Performance  创建Performance需要PlaceOrderCommand
    
    //先创建PlaceOrderCommand 传入Performance  再创建Performance传入Printlog
    
    //先执行Printlog的excete()方法,执行完日志操作之后 调用再执行Performance中的excute()方法,执行完日志操作之后 执行其中的excute()方法。
    
    Command cmd=new Printlog (new Performance (new PlaceOrderCommand ()));
    
    cmd.excute()
    
    //如果只希望打印日志不希望进行性能统计
    
    Command cmd=new Printlog (new PlaceOrderCommand ());
    
    cmd.excute();
    
    }

    可以使用任意数量的装饰器,还可以任意次序执行。最终的业务逻辑放在最后,如果需要先执行业务逻辑再统计数据,也只需要更改本方法中的执行顺序而已。

    不和别人一样,不复制只真正理解
  • 相关阅读:
    关于cocos2dx之lua使用TableView
    设计模式-----工厂模式
    android YUV Sensor配置Camera应用的flash auto菜单
    AngularJS实现cookie跨域
    julia/pyplot 绘图加入标签和标题
    自己写unicode转换ascii码,wchar*到char*
    Android笔记——Activity中的数据传递案例(用户注冊)
    IIS预编译提升载入速度
    Python Tkinter 基础控件学习
    spfile
  • 原文地址:https://www.cnblogs.com/Vinlen/p/12759810.html
Copyright © 2011-2022 走看看