工厂模式

99 阅读1分钟

工厂模式顾名思义就是像工厂一样能批量解决或者说完成某一逻辑

这是最简单的工厂模式,说白了就是定义一个能解决具体业务的函数,然后实例化

function Person(name,age,sex){
    this.name = name
    this.age = age
    this.sex = sex
}

new Person()

复杂一点的工厂模式

定义一个父类:是一个抽象类,里面写了公共的方法,不被用于实例化,用于被子类继承
子类:是一个具体类,里面写了实现自身实例的方法
// 父类
function CarShop(name) {
  this.name = name;
  this.getName = function () {
    return this.name;
  };
}
CarShop.prototype = {
  constructor: CarShop,
  sellCar: function () {
    let car = this.createCar();
    car.a();
    car.b();
    return car;
  },
  createCar: function () {
    throw new Error("父类不能直接实例,需要子类");
  },
};

function extend(sub,sup){
    // 使用原型链继承
    let F = function(){}
    F.prototype = sup.prototype
    sub.prototype = new F()
    sub.prototype.constructor = sub
    sub.sup = sup.prototype
}

// 子类
function CarChild(name){
    this.name = name
    CarShop.call(this.name)
}
extend(CarChild,CarShop)

CarChild.prototype.createCar = function(){
    let a  = function(){
        console.log('执行了a');
    }
    let b  = function(){
        console.log('执行了b');
    }
    return {
        a,b
    }
}
let cc = new CarChild('比亚迪')
console.log(cc.createCar());

其实更好的方式可以使用es6class的方式来实现类似原型链继承的方式,那样会更简单,好理解