设计模式之工厂模式

工厂模式

简单工厂模式

  • 批量生产对象的时候没有必要一个一个对象去创建,减少重复性代码。
  1. 在函数内部创建一个空对象
  2. 再给这个对象添加属性和方法
  3. 将包装好的对象返回处理啊
function createPerson(name) {
    const o = {};
    o.name = name;
    o.getName = function() {
        console.log(this.name);
    }
    return o;
}

const person1 = createPerson('lazy');
person1.getName(); // lazy
console.log(person1.name); // lazy

工厂方法

function Person(name) {
    this.name = name;
}
Person.prototype.getName = function() {
    console.log(this.name)
}
function Car(model) {
    this.model = model;
}

Car.prototype.getModel = function() {
    console.log(this.model)
}

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
}
const person1 = new create('person', '张三');
person1.getName(); // 张三
const car1 = create('car', 'Benz');
car1.getModel(); // Benz
  • new create('person', '张三') 发生了什么?

    1. 将 person1 的 proro(原型链) 指向了 create 的 prototype(原型)
  • new thistype 发生了什么?

    1. new thistype = new Person('张三')
    2. 将 create 的 proro(原型链) 指向了 Person 的 prototype(原型)

ES6 class 写法

class Person {
    constructor(name) {
        this.name = name;
    }
    getName() {
        console.log(this.name);
    }
}
class Car {
    constructor(model) {
        this.model = model;
    }
    getModel() {
        console.log(this.model);
    }
}
class Create {
    static createFather = {
        person: Person,
        car: Car
    }
    constructor(type, param) {
        return new Create.createFather[type](param);
    }
    static create = function(...args) {
        return new this(...args)
    }
}
// Create.prototype.person = Person;
// Create.prototype.car = Car;
const person1 = new Create('person', '张三');
person1.getName(); // 张三
const car1 = Create.create('car', 'Benz');
car1.getModel(); // Benz
posted @ 2021-01-23 18:06  懒惰ing  阅读(95)  评论(0编辑  收藏  举报