zoukankan      html  css  js  c++  java
  • 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')
    

      

  • 相关阅读:
    地图的可视化--Folium
    GIS性能策略
    计算多边形中心线
    生成凹壳
    路径分析之NetworkX实例
    网络分析之networkx(转载)
    网络分析之Pgrouting(转载)
    颜色空间变换(RGB-HSV)
    计算坡度与坡向
    计算山体阴影
  • 原文地址:https://www.cnblogs.com/diantao/p/13667458.html
Copyright © 2011-2022 走看看