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

    装饰者模式,Decorator Pattern。在不改变原类和继承的情况下动态扩展对象功能,通过包装一个对象来实现一个新的具有原对象相同接口的新的对象。

    装饰者模式特点:

        1. 不修改原对象的原本结构来进行功能添加。
        2. 装饰对象和原对象具有相同的接口,可以使客户以与原对象相同的方式使用装饰对象。
        3. 装饰对象中包含原对象的引用,即装饰对象为真正的原对象在此包装的对象。

    装饰者模式可以为对象添加功能从而代替了编写大量子类的情况。
        以JS设计模式实例为例,首先自行车商店有4种类型自行车:

      

    <!DOCTYPE HTML>
    <html>
    <body>
    
    <script>
        function ABicycle(){ }
        ABicycle.prototype = {
            wash : function(){ },
            ride : function(){ },
            getPrice : function(){
                return 999;
            }
        }
    
        function extend( subClass, superClass ){
            var F = function(){};
            F.prototype = superClass.prototype;
            subClass.prototype = new F();
            subClass.prototype.constructor = subClass;
    
            // 此处指向superClass的prototype 比直接保存superClass使用更为方便
            subClass.superclass = superClass.prototype;
            if( superClass.prototype.constructor === Object.prototype.constructor ){
                superClass.prototype.constructor = superClass;
            }
        }
    
        function BicycleDecorator( bicycle ){
            this.bicycle = bicycle;
        }
        BicycleDecorator.prototype = {
            wash : function(){
                return this.bicycle.wash();
            },
            ride : function(){
                return this.bicycle.ride();
            },
            getPrice : function(){
                return this.bicycle.ride();
            }
        }
    
        var BicycleBell = function( bicycle ){
            // 继承 BicycleDecorator 内部 this定义的数据或者方法
            BicycleBell.superclass.constructor(  bicycle );
        }
        // 继承 BicycleDecorator.prototype 并且添加 BicycleBell.superclass 指向 BicycleDecorator.prototype
        extend( BicycleBell, BicycleDecorator );
        // 添加或者修改
        BicycleBell.prototype.bell = function(){
            console.log("ding! ding! ding!");
        }
        BicycleBell.prototype.getPrice = function(){
            console.log(this)
            return this.bicycle.getPrice() + 100;
        }
    
        var bicycleA = new ABicycle();
        bicycleA = new BicycleBell( bicycleA );
        console.log(bicycleA.getPrice());
    
    
    
    
    
    
    
    </script>
    
    </body>
    </html>
    

      

  • 相关阅读:
    webpack--前端自动化工具
    Vue--入门篇
    集千篇理论,终得深拷贝与浅拷贝的初解
    事件循环--eventloop
    对象的属性(变量+对象)
    集千篇理论精华,感悟对同步和异步的理解
    vue--先决篇
    js的基本语法规范
    python 模块加载错误总结
    Python logging模块无法正常输出日志
  • 原文地址:https://www.cnblogs.com/sean-/p/4942289.html
Copyright © 2011-2022 走看看