js 简单工厂模式

简单工厂模式,又叫静态工厂模式.由一个工厂对象决定创建某一种产品对象的实例.主要用于创建某一类对象.

var basketball  = function(){
    this.title = '篮球';
}

basketball.prototype  = {
    getMenberNum :function(){
        console.log('5个人');
    },
    getPlayAction:function(){
        console.log('投篮')
    }
}


var football = function(){
    this.title = '足球';
}

football.prototype = {
    getMenberNum :function(){
        console.log('11个人');
    },
    getPlayAction:function(){
        console.log('射门')
    }
}

var factory = function(type){
    switch(type){
        case 'basketball': return new basketball();
        case 'football': return new football();
    }
}


//然后我们就可以这么用
oPlay = factory('basketball');
oPlay.getMenber();

oPlay2 = factory('football');
oPlay2.getPlayAction();

如果两个类的共有属性比较多的时候,我们可以这样用

var factory = function(name,age,sex,national){
    var obj = {};
    obj.name = name;
    obj.age = age;
    obj.sex = sex;
    switch(national){
        case 'Chinese':
            obj.speak = function(){
                console.log('Speak Chinese');
            };
            break;
        case 'England':
            obj.speak = function(){
                console.log('SpeakEnglish')
            };
            break;
    }
    return obj;
}

var person = new factory("Jack",'15','Man',"Chinese");
person.speak();

你可能感兴趣的:(javascript学习笔记)