js 原廠模式

來源:互聯網
上載者:User

標籤:

原廠模式是管理對象的一種設計模式,通過向外提供一個公用方法用於建立對象。把使用對象的部分與建立對象的部分分離,建立對象部分與對象建立前的初始化分離,職責分離。jQuery.Callbacks是一個工廠,每次調用都會返回一個對象,並且根據傳入的不同參數值返回的對象具有不同的特徵。

1.簡單原廠模式

在Factory 方法中,根據傳入的參數建立相應的對象,並且返回。

  function Orange(){        this.color = ‘orange‘;    }    function Apple(){        this.color = ‘red‘;    }    function Banana(){        this.color = ‘yellow‘;    }    // 建立對象的工廠    function SimpleFactory(type){        var fruit = null;        switch(type){            case ‘orange‘:                fruit = new Orange();                break;            case ‘apple‘:                fruit = new Apple();                break;            case ‘banana‘:                fruit = new Banana();        }        return fruit;    }    //測試    var apple = SimpleFactory(‘apple‘);    console.log(apple.color);    var banana = SimpleFactory(‘banana‘);    console.log(banana.color);

 簡單原廠模式只能產生Factory 方法中指定類型的對象,當需要添加其他類型的對象時,需要在Factory 方法中添加相對應的代碼。

2.原廠模式

原廠模式對簡單原廠模式改進,可以擴充新的類型的對象,並且不用修改Factory 方法。

  function Fruit(){}    Fruit.prototype.say = function(){        return ‘hello,my name is ‘ + this.name;    }    Fruit.Apple = function (){        this.name = ‘apple‘;    }    Fruit.Banana = function(){        this.name = ‘banana‘;    }    Fruit.Orange = function(){        this.name = ‘orange‘;    }    Fruit.factory = function(type){        var fruit = null;        //如果建構函式不存在,返回        if(typeof Fruit[type] !== ‘function‘){            return;        }        //使用原型繼承父類        if(typeof Fruit[type].prototype.getColor !== ‘function‘){            Fruit[type].prototype = new Fruit();        }        //建立對象        fruit = new Fruit[type]();        return fruit;    }    //測試    var apple = Fruit.factory("Apple");    console.log(apple.say());

 

js 原廠模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.