Javascript設計模式學習之Decorator(裝飾者)模式

抽象decorator模式

使用jQuery的裝飾者模式

jQuery.extend()容許咱們在運行時或者在隨後一個點上動態地將兩個或兩個以上的對象(和它們的屬性)一塊兒擴展(或合併)爲一個單一對象。code

定義三個對象: defaults、options、settings,目的是爲了裝飾defaults對象,將options的額外功能附加到defaults上。對象

var decoratorApp = decoratorApp || {};
//定義要使用的對象
decoratorApp = {
   defaults: {
      validate: false,
      limit: 5,
      name: "foo",
      welcome: function(){
          console.log("welcome!");
      }
   },

   options:{
       validate: true,
       name: "bar",
       helloWorld: function(){
           console.log("hello,world");
       }
   },

   settings: {},

   printObj: function(obj){
       var arr = [],
           next;
       $.each(obj,function(key,val){
           next = key + ":";
           next += $.isPlainObject(val) ? printObj(val) : val;
           arr.push(next);
       });
       
       return "{" + arr.join(",") + "}";
   }
};

decoratorApp.settings = $.extend({},decoratorApp.defaults,decoratorApp.options);
//打印
decoratorApp.printObj(decoratorApp.settings);
相關文章
相關標籤/搜索