【设计模式】构造器模式和原型模式

构造器模式

如果我们系统中有多个员工,创建每一个员工都需要 new 一下,出现很多重复代码,所以我们可以将他们写成一个构造函数,然后通过传入的不同参数创建不同的员工。

js 复制代码
function Employee(name, age) {
    this.name = name
    this.age = age
    this.toString = function() {
        return `name: ${this.name}, age: ${this.age}`
    }
}

const employee1 = new Employee('张三', 18)
console.log("=>(index.js:7) employee1", employee1); 
//=>(index.js:7) employee1 Employee { name: '张三', age: 18, toString: [Function (anonymous)] }

原型模式

以上代码中toString 方法,每次 new 一个对象都需要重新创建一个,而这个方法却是每一个 Employee 共有的,所以能不能把这个方法提取到一个公共的地方捏?

此时就需要我们使用原型模式,将 toString 方法挂载到 Employee 的原型上。

js 复制代码
function Employee(name, age) {
    this.name = name
    this.age = age
}

Employee.prototype.toString = function () {
    return `name: ${this.name}, age: ${this.age}`
}

const employee1 = new Employee('张三', 18)
console.log("=>(index.js:7) employee1", employee1);
//=>(index.js:7) employee1 Employee { name: '张三', age: 18 }
console.log(employee1.toString())
// name: 张三, age: 18

那假如我们使用 ES6 写法呢?

js 复制代码
class Employee {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    toString() {
        return `name: ${this.name}, age: ${this.age}`
    }
}
const employee1 = new Employee('张三', 18)
console.log("=>(index.js:7) employee1", employee1);
//=>(index.js:7) employee1 Employee { name: '张三', age: 18 }
console.log(employee1.toString())
// name: 张三, age: 18

很神奇!toString 直接被挂载到原型上!

所以说,es6 类的写法同时兼顾了构造器模式和原型模式。

应用场景有比如组件的复用,状态管理等。

相关推荐
执笔论英雄5 小时前
【大模型训练】加载load_state 中的一些技巧 工厂设计模式
设计模式
gladiator+10 小时前
Java中的设计模式------策略设计模式
java·开发语言·设计模式
在未来等你13 小时前
AI Agent设计模式 Day 2:Plan-and-Execute模式:先规划后执行的智能策略
设计模式·llm·react·ai agent·plan-and-execute
在未来等你19 小时前
AI Agent设计模式 Day 3:Self-Ask模式:自我提问驱动的推理链
设计模式·llm·react·ai agent·plan-and-execute
xiaodaidai丶1 天前
设计模式之策略模式
设计模式·策略模式
_院长大人_1 天前
设计模式-工厂模式
java·开发语言·设计模式
王道长服务器 | 亚马逊云2 天前
AWS + 苹果CMS:影视站建站的高效组合方案
服务器·数据库·搜索引擎·设计模式·云计算·aws
在未来等你2 天前
AI Agent设计模式 Day 1:ReAct模式:推理与行动的完美结合
设计模式·llm·react·ai agent·plan-and-execute
火鸟22 天前
给予虚拟成像台尝鲜版十,完善支持HTML原型模式
原型模式·通用代码生成器·给予虚拟成像台·给予·html原型模式·快速原型·rust语言
乐悠小码2 天前
Java设计模式精讲---03建造者模式
java·设计模式·建造者模式