JavaScript设计模式 -- 工厂模式

案例一:

function Cat(name, color) {
    return {
        name: name || 'cat',
        color: color || 'black'
    }
}

const cat1 = new Cat('kity', 'white')
const cat2 = new Cat()

  

案例二:

const BicycleShop = function () {}

BicycleShop.prototype = {
    sellBicycle: function (model) {
        const bicycle = this.createBicycle(model)
        return bicycle
    },
    createBicycle: function(model) {
        throw new Error('before use it, must be use keyword new')
    }
}

const OracleBicycle = function () {}
inherits(OracleBicycle, BicycleShop)
OracleBicycle.prototype.createBicycle = function(model) {
    let bicycle
    switch(model) {
        case 'speedster':
            bicycle = new OracleSpeedster()
            break
        case 'lowrider':
            bicycle = new OracleLowrider()
            break
        case 'Alien':
            bicycle = new OracleAlien()
            break
        default:
            bicy = new OracleComfortCruiser()
    }
    return bicycle
}
function OracleSpeedster() {
    console.log('OracleSpeedster')
}
function OracleLowrider() {
    console.log('OracleLowrider')
}
function OracleAlien() {
    console.log('OracleAlien')
}
function OracleComfortCruiser() {
    console.log('OracleComfortCruiser')
}

const IBMBicycleShop = function () {}
inherits(IBMBicycleShop, BicycleShop)
IBMBicycleShop.prototype.createBicycle = function(model) {
    let bicycle
    switch(model) {
        case 'speedster':
            bicycle = new IBMSpeedster()
            break
        case 'lowrider':
            bicycle = new IBMLowrider()
            break
        case 'Alien':
            bicycle = new IBMAlien()
            break
        default:
            bicycle = new IBMComfortCruiser()
    }
    return bicycle
}
function IBMSpeedster() {
    console.log('IBMSpeedster')
}
function IBMLowrider() {
    console.log('IBMLowrider')
}
function IBMAlien() {
    console.log('IBMAlien')
}
function IBMComfortCruiser() {
    console.log('IBMComfortCruiser')
}

function inherits(child, base) {
    child.prototype = Object.create(base.prototype)
}

const oracleShop = new OracleBicycle()
oracleShop.sellBicycle('speedster')

const ibmShop = new IBMBicycleShop()
ibmShop.sellBicycle('IBMAlien')

  

posted @ 2020-09-14 16:24  点点乐淘淘  阅读(141)  评论(0编辑  收藏  举报