设计模式之工厂模式

工厂模式

简单工厂模式

  • 批量生产对象的时候没有必要一个一个对象去创建,减少重复性代码。
  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 @   懒惰ing  阅读(98)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示