JS設計模式之原廠模式

來源:互聯網
上載者:User

標籤:span   comm   logs   ons   mon   create   Factory 方法   name   func   

簡單原廠模式

又叫靜態Factory 方法:由一個工廠對象決定用那一種類來建立產品,主要用來建立同一類對象,是類的執行個體化的封裝。

    var PlayBaseketball = function () {        this.neededPeople = 15;    };    PlayBaseketball.prototype.rule = function () {        console.log(‘運球,傳球,投籃,‘);    };    var playFootball = function () {        this.neededPeople = 20;    };    playFootball.prototype.rule = function () {        console.log(‘帶球,射球‘);    };    //運動    var ballFactory = function (name) {        switch(name) {            case ‘baseketball‘:                return new PlayBaseketball();            case ‘football‘:                return new playFootball();            default:                throw ‘我這裡沒有你要的東西‘;        }    }

 更簡單的方式是使用類似於適配的方式做差異化管理:

    function createBall(name) {        var temp = new Object();        //公用部分        var common = function () { }        //差異部分        if(name === ‘baseketball‘) {            temp...        } else if (name === ‘football‘) {            temp...        } else {            throw ‘我沒有你要的東西‘;        }    }

 

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.