工厂模式-封装

231 阅读1分钟

工厂模式

工厂模式是一种简单的设计模式,主要是创建对象用的,如果有需求需要重复的创建对象,就可以试试用工厂模式的思路去完成

      function Person(name) {
            this.name = name
        }
        Person.prototype.getName = function () {
            console.log(this.name)
        }
        function Car(modul) {
            this.modul = modul
        }
        Car.prototype.getModul = function () {
            console.log(this.modul)
        }
        function create(type, param) {
            if (this instanceof create) {
                return new this[type](param)
            } else {
                return new create(type,param)
            }
        }
        create.prototype = {
            person: Person,
            car: Car
        }   
        let p = new create('person', 'lei')
        let c = create('car', 'ma')
        p.getName() // 'lei'
        c.getModul() //'ma'