zoukankan      html  css  js  c++  java
  • js设计模式--结构型--装饰器模式

      结构型:装饰器模式

      装饰器模式,又称为装饰者模式。

      定义:在不改变原对象的基础上,通过对其进行包装扩展,使原有对象可以满足用户更复杂的需求。

      应用场景:需求 --  业务中的按钮在点击之后都弹出 【请先登录】的弹框。

    html
    <button id='open'>点击打开</button>
    <button id='close'>关闭弹框</button>

    //
    弹框创建逻辑 const Modal = (function() { let modal = null return function() { if(!modal) { modal = document.createElement('div') modal.innerHTML = '您还未登录哦~' modal.id = 'modal' modal.style.display = 'none' document.body.appendChild(modal) } return modal } })() // 点击打开按钮展示模态框 document.getElementById('open').addEventListener('click', function() { // 未点击则不创建modal实例,避免不必要的内存占用 const modal = new Modal() modal.style.display = 'block' }) // 点击关闭按钮隐藏模态框 document.getElementById('close').addEventListener('click', function() { const modal = document.getElementById('modal') if(modal) { modal.style.display = 'none' } })

      这个功能就算实现了,如果后面需求改变,让弹框被关闭后把按钮文字改成 “快去登录”,同时按钮置灰。

      那么我们就不在原有的代码上进行修改,这块就可以使用 装饰器模式。

    // 定义打开按钮
    class OpenButton {
      // 点击后展开 modal 旧逻辑
      onClick() {
        const modal = new Modal();
        modal.style.display = "block";
      }
    }
    
    // 定义按钮对应的装饰器
    class Decorator {
      // 将按钮实例传入
      constructor(open_button) {
        this.open_button = open_button;
      }
      onClick() {
        this.open_button.onClick();
        // 包装一层 新逻辑
        this.changeButtonStatus();
      }
      changeButtonStatus() {
        this.changeButtonText();
        this.disableButton();
      }
      changeButtonText() {
        const btn = document.getElementById("open");
        btn.innerHTML = "快去登录";
      }
      disableButton() {
        const btn = document.getElementById("open");
        btn.setAttribute("disabled", true);
      }
    }
    
    const openButton = new OpenButton();
    // 把实例按钮传入 Decorator,以便以后对Decorator 进行扩展。
    const decorator = new Decorator(openButton);
    
    document.getElementById("open").addEventListener("click", function () {
      // openButton.onClick()Decorator
      // 此处可以分别尝试两个实例的onClick方法,验证装饰器是否生效
      decorator.onClick();
    });

      注:React中的 HOC高阶组件就是装饰器模式在React 中的实践。

      

      

  • 相关阅读:
    HDU 5912 Fraction (模拟)
    CodeForces 722C Destroying Array (并查集)
    CodeForces 722B Verse Pattern (水题)
    CodeForces 722A Broken Clock (水题)
    CodeForces 723D Lakes in Berland (dfs搜索)
    CodeForces 723C Polycarp at the Radio (题意题+暴力)
    CodeForces 723B Text Document Analysis (水题模拟)
    CodeForces 723A The New Year: Meeting Friends (水题)
    hdu 1258
    hdu 2266 dfs+1258
  • 原文地址:https://www.cnblogs.com/Sabo-dudu/p/14652336.html
Copyright © 2011-2022 走看看