zoukankan      html  css  js  c++  java
  • js原生设计模式——12装饰者模式

    1、面向对象模式装饰者

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>面向对象—Decorator装饰者模式</title>
        <script type="text/javascript">
        //给实例对象(注:不影响类)动态添加职责的方式叫做Decorator装饰者模式,较继承,此方法更为灵活。
        //先声明一个原始飞机类
        var Plane = function(){};
        Plane.prototype.fire = function(){
            console.log('发射子弹');
        }
        //接下来声明两个装饰类,他们之间靠this所指向的实例对象连接
        var MissleDecorator = function(plane){//发射导弹装饰类
            this.plane = plane;
        }
        MissleDecorator.prototype.fire = function(){
            this.plane.fire();
            console.log('发射导弹');
        }
        var AtomDecorator = function(plane){//发射原子弹装饰类
            this.plane = plane;
        }
        AtomDecorator.prototype.fire = function(){
            this.plane.fire();
            console.log('发射原子弹');
        }
        //测试用例
        var plane = new Plane();
        plane = new MissleDecorator(plane);//技巧在于这里的实例传参,起到纽带作用
        plane = new AtomDecorator(plane);
        plane.fire();
        //本例已经通过验证
        </script>
    </head>
    <body>
    </body>
    </html>

    2、函数式编程实现装饰者效果——其实是职责链模式

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8"></meta>
        <title>函数式编程实现装饰者效果——其实是职责链模式</title>
    </head>
    <body>

    </body>
    <script type="text/javascript">
        var plane = {   //声明单体对象plane
            fire:function(){
                console.log('发射子弹');
            }
        }
        var missleDecortor = function(){   //声明“发射导弹”功能函数
            console.log('发射导弹');
        }
        var atomDecortor = function(){   //声明“发射原子弹”功能函数
            console.log('发射原子弹');
        }
        //缓存原plane对象的fire模块
        var fire1 = plane.fire;
        //重写,拓展plane.fire
        plane.fire = function(){
            fire1();
            missleDecortor();   //拓展发射导弹功能
        }
        //再次缓存,再次重写
        var fire2 = plane.fire;
        plane.fire = function(){
            fire2();
            atomDecortor();
        }
        plane.fire();
    </script>
    </html>

  • 相关阅读:
    一篇文章教会你在Windows和Linux系统下搭建Nginx
    【红日安全-VulnStack】ATT&CK实战系列——红队实战(二)
    绕过WAF进行常见Web漏洞利用
    Mac mysql 5.7.x 设置服务开机自启动
    Mac mysql 5.7启动报错,解决之道 The server quit without updating PID file
    阿里云Centos7 安装mysql5.7 报错:./mysqld: error while loading shared libraries: libaio.so.1: cannot open shared object file: No such file or directory
    Python 反序列化漏洞学习笔记
    Jmeter二次开发——基于Java请求
    环境篇:Atlas2.1.0兼容CDH6.3.2部署
    synchronized 是王的后宫总管,线程是王妃
  • 原文地址:https://www.cnblogs.com/koleyang/p/5039449.html
Copyright © 2011-2022 走看看