js设计模式 --- 装饰设计模式

装饰设计模式

每种设都有其独特的应用场景和解决问题的方式, 装饰设计模式是动态的为对象添加新的功能, 是一种用于代替继承的技术,无需通过继承增加子类就能扩展对象的新功能。使用对象的关联关系代替继承关系,更加灵活,同时避免类型体系的快速膨胀, 这种模式适合新添加的功能不足以用继承为代价解决问题的情况时使用 –
杀鸡焉用宰牛刀 ^_^

装饰设计模式: 动态地为一个对象添加一些额外的职责,若要扩展一个对象的功能,装饰者提供了比继承更有弹性的替代方案。

结构图:
《js设计模式 --- 装饰设计模式》

  • 接口

    var Bicycle = new Interface('Bicycle', ['assemble', 'wash', 'repair', 'getPrice']);
  • 对象类

    var AcmeComfortCuiser = function(){
        
    };
    AcmeComfortCuiser.prototype = {
        assemble: function(){
            
        },
        wash: function(){
            
        },
        repair: function(){
            
        },
        getPrice: function(){
            
        }
    }
  • 装饰类

    var BicycleDecorator = function(bicycle){
        Interface.ensureImplements(bicycle, Bicycle);
        this.bicycle = bicycle;
    };
    BicycleDecorator.prototype = {
        assemble: function(){
            return this.bicycle.assemble();
        },
        wash: function(){
            return this.bicycle.wash();
        },
        repair: function(){
            return this.bicycle.repair();
        },
        getPrice: function(){
            return this.bicycle.getPrice();
        }
    }
  • 拓展类

        var HeadlightDecorator = function(bicycle){
            BicycleDecorator.call(this, bicycle);
        };
        extend(HeadlightDecorator, BicycleDecorator);
        HeadlightDecorator.prototype.getPrice = function(){
            return this.bicycle.getPrice() + 15.00;
        }
    原文作者:设计模式
    原文地址: https://segmentfault.com/a/1190000013293431
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞