1. 程式人生 > >js38---門面模式

js38---門面模式

info dev style dom 程序 ddr 2個 {} ...

(function(){
    //門面
    function addEvebtFacade(el,type,fn){
        if(window.addEventListener){
            //使用與火狐瀏覽器
            alert(1);
            el.addEventListener(type,fn,false);
        }else if(window.attachEvent){
            //適用於IE的
            alert(2);
            el.attachEvent("on"+type,fn);
        }
else{ alert(3); el["on"+type] = fn; } } document.write("<a id=‘but1‘ href=‘#‘>click</a>"); var el = document.getElementById("but1"); addEvebtFacade(el,"click",function(){ alert("ok") }) })()
/**
 * 用2個DAO來體現門面模式
 */
(function(){
    
//人員類 var PersonDao = new Interface("PersonDao",["getInfo","learn", "marry"]); var Person = function(){ this.name = "YUNFENGCHENG"; this.address = "BEIJING"; this.getInfo = function(){ return "名字: "+this.name +" 地址: "+this.address; }
this.learn = function(){ document.write("學習"); } this.marry = function(){}; //驗證實現的接口 Interface.ensureImplements(this,PersonDao); } //DOG DAO var DogDao = new Interface("DogDao",["call","run","getInfo"]); var Dog = function(){ this.name = "DAHUANG"; this.getInfo = function(){ return "狗狗的名字: "+this.name; } this.run = function(){}; this.call = function(){}; Interface.ensureImplements(this,DogDao); } //需求是現在需要給養的夠辦了相應寵物領養證件 需要人和狗狗的信息可以 //1.不用門面 //客戶端程序 function action(person,dog){ //當做養狗證的號碼 var r = "GG"+new Date().getDate()+Math.floor(Math.random()*11); var str = "辦證成功 :編號 "+r +"<br>主人信息: "+person.getInfo() +"<br>狗狗的信息: "+dog.getInfo(); document.write(str); } action(new Person(),new Dog()); document.write("<br>.........................."); //使用門面模式 //負載的事交給門面來做 function facade(person,dog){ //當做養狗證的號碼 var r = "GG"+new Date().getDate()+Math.floor(Math.random()*11); this.str = "辦證成功 :編號 "+r +"<br>主人信息: "+person.getInfo() +"<br>狗狗的信息: "+dog.getInfo(); } facade.prototype.action = function(){ return this.str; } //客戶端程序 function action2(person,dog){ document.write(new facade(person,dog).action()); } action2(new Person(),new Dog()) //用了門面模式客戶端代碼就變的如此的簡單了 })()

js38---門面模式