單體模式的概念是確保一個類別只有一個物件,並提供對該物件的全域操作,一般來說,當我們利用同一個類別建立實體物件時,每次建立得到的物件都會是不同的。
    function Cat() {
        if (typeof Cat.instance === "object") {
            return Cat.instance;
        }
        this.name = "kitty";
        Cat.instance = this;
    }
    
    Cat.prototype.move = function() {
        return this.name + " move";
    };
    
    var cat1 = new Cat();
    var cat2 = new Cat();
    
    // 驗證為同一個物件
    
    console.log(cat1 === cat2); //true
    cat1.name = "coco";
    console.log(cat2.move()); //"coco"
    
概念類似日常生活當中,每個人都只有一個身份證號碼,若證件遺失仍然是用原有的身分證號碼做補發,並不會因此產生一個新的身分證號碼。
優點
缺點
簡單工廠模式是使用一個類別來生成各種不同的物件,由一個方法來決定到底要創建哪個類別的物件,而這些物件基本上都擁有相同的介面,可取得所需要的物件。
    
    // 在 Function 原型上擴充繼承方法
    Function.prototype.inherits = function(superCtor) {
        Object.setPrototypeOf(this.prototype, superCtor.prototype);
        this.super = superCtor.prototype;
    };
    function Drink() {
    }
    Drink.prototype.showColor = function() {
        console.log("Drink color:" + this.color);
    };
    function Coffee() {
        this.color = "brown";
    }
    Coffee.inherits(Drink);
    function Milk() {
        this.color = "white";
    }
    Milk.inherits(Drink);
    function OrangeJuice() {
        this.color = "orange";
    }
    OrangeJuice.inherits(Drink);
    var factory = {
        build: function (type) {
            return new type();
        }
    };
    
    var milk = factory.build(Milk);
    milk.showColor(); //Drink color:white
    
一間工廠不會只生產一種產品,因此透過工廠模式可產生不同的產品,如同生活中到便利商店買飲料,可選擇可樂、茶類、牛奶等等。
優點
缺點
迭代器模式是一種提供簡單操作介面,而不用暴露資料來源的方法或更動它,也就是說,提供一個操作介面,讓其他人利用這個介面對資料元素做操作。
    var iterator = (function() {
        var index = 0,
            data = [1, 2, 3, 4, 5],
            length = data.length;
        return {
            next: function() {
                index = index + 1;
            },
            hasNext: function() {
                return index < length;
            },
            first: function() {
                index = 0;
            },
            current: function() {
                return data[index];
            }
        };
    })();
    
    iterator.first();
    while (iterator.hasNext()) {
        console.log(iterator.current());
        iterator.next();
    }
    
生活中夾娃娃機就好像是迭代器,只能操作搖桿和控制按鈕。
優點
連假終於開始啦,對於先存稿的人嗤之以鼻哼哼 ( 我好羨慕有存稿的人 RRR
參考資料:
Tommy - 深入 JavaScript 核心課程