javascript中常見的三種開發模式


一、單例模式:

  所謂單例模式,即保證一個類只有一個實例,並提供一個訪問它的全局訪問點。

  

<script type="text/javascript">
            //一個類有某個實例,就用這個實例,沒有的話,就新生成一個實例

            var singleTon = (function(){
                var _instance = null;
                
                function Foo(){
                    this.a = "**";
                    this.b = "**";
                }
                Foo.prototype.fn = function(){
                    
                }

                return {
                    getInstance:function(){
                        if(!_instance){
                            _instance = new Foo();
                        }
                        return _instance;
                    }
                }
            })();
 console.log(singleTon.getInstance()==singleTon.getInstance());
            
             
        </script>

  單例模式實現彈出層:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            div{
                height: 100px;
                width: 100px;
                background: red;
            }
        </style>
    </head>
    <body>
        <input type="button" id="btn" value="彈出層" />
        
        <script type="text/javascript">
            (function(){
                var oBtn = document.getElementById("btn");
                var _instance = null;
                //創建彈窗類
                function PopBox(){
                    this.node = document.createElement("div");
                    document.body.appendChild(this.node);
                }
                oBtn.onclick = function(){
                    if(!_instance){
                        _instance = new PopBox;
                    }
                }
                
            })();
        </script>
    </body>
</html>

二、觀察者模式:

  所謂觀察者模式,即(發布-訂閱模式):其定義對象間一種一對多的依賴關系,當一個對象的狀態發生改變時,所有依賴於它的對象都將得到通知。

  

<script type="text/javascript">
        var observer = {
            regist:function(eventName,callback){
                if(!this.obj){
                    this.obj = {};
                }
                if(!this.obj[eventName]){
                    this.obj[eventName] = [callback];
                }else{
                    this.obj[eventName].push(callback);
                }
                
                
            },
            emit:function(eventName){
                if(this.obj[eventName]){
                    for(var i = 0; i < this.obj[eventName].length; i++){
                        this.obj[eventName][i]();
                    }
                }
            },
            remove:function(eventName,callback){
                if(this.obj[eventName]){
                    for(var i = 0; i < this.obj[eventName].length;i++){
                        if(this.obj[eventName][i]==callback){
                            this.obj[eventName].splice(i,1);
                        }
                    }
                }
            }
        };
        
        //購物車模塊注冊的事件
        observer.regist("loginSucess",function(){
            console.log("購物車模塊發生改變");
        });
        //個人信息模塊注冊的事件
        observer.regist("loginSucess",function(){
            console.log("個人信息模塊發生改變");
        });
        
        observer.emit("loginSucess");//
    </script>

  觀察者模式常見面試題:

  

<script type="text/javascript">
            var Event = {
                // 通過on接口監聽事件eventName
                // 如果事件eventName被觸發,則執行callback回調函數
                on: function(eventName, callback) {
                    //你的代碼 注冊事件
                    if(!this.obj){
                        Object.defineProperty(this,"obj",{
                            value:{},
                            enumerabel:false
                        })
                    }
                    if(!this.obj[eventName]){
                        this.obj[eventName] = [callback];
                    }else{
                        this.obj[eventName].push(callback);
                    }
                },
                // 觸發事件 eventName
                emit: function(eventName) {
                    //你的代碼 發布事件
                    if(this.obj[eventName]){
                        for(var i = 0; i < this.obj[eventName].length; i++){
                            this.obj[eventName][i](arguments[1]);
                        }
                    }
                }
            };
            
            
            // 測試1
            Event.on('test', function(result) {
                console.log(result);
            });
            Event.on('test', function() {
                console.log('test');
            });
            Event.emit('test', 'hello world'); // 輸出 'hello world' 和 'test'
            
            
        
            // 測試2
            var person1 = {};
            var person2 = {};
            
            Object.assign(person1, Event);
            Object.assign(person2, Event);
            
            person1.on('call1', function() {
                console.log('person1');
            });
            
            person2.on('call2', function() {
                console.log('person2');
            });
            
            person1.emit('call1'); // 輸出 'person1'
            person1.emit('call2'); // 沒有輸出
            person2.emit('call1'); // 沒有輸出
            person2.emit('call2'); // 輸出 'person2'

        </script>

三、組合模式:

  組合模式又稱部分-整體模式,將對象組合成樹形結構以表示“部分整體”的層次結構。

<script type="text/javascript">
        //訂單系統  票務系統  酒店系統
        
        function Ticket(){
            
        }
        Ticket.prototype.create = function(){
            console.log("創建了機票訂單");
        }

        function Hotel(){
            
        }
        Hotel.prototype.create = function(){
            console.log("創建了酒店訂單");
        }

        function Order(){
            this.orders = [];
        }
        Order.prototype.addOrder = function(order){
            this.orders.push(order);
            return this;
        }
        Order.prototype.create = function(){
            for(var i = 0; i < this.orders.length; i++){
                this.orders[i].create();
            }
        }
        
        var order = new Order();
        order.addOrder(new Ticket()).addOrder(new Ticket())
        .addOrder(new Hotel());
        
        order.create();
    </script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM