结合 ES6 类编写JavaScript 创建型模式

 更新时间:2022年07月21日 09:07:15   作者:​ 天行无忌​  
这篇文章主要介绍了结合ES6类编写JavaScript创建型模式,本文开始系统性的对20多种JavaScript 设计模式进行简单概述,然后结合ES6类的方式来编写实例代码展示其使用方式,需要的朋友可以参考一下

前言

什么是设计模式?

设计模式是软件设计中常见问题的解决方案,这些模式很容易重复使用并且富有表现力。

在软件工程中,设计模式(design pattern)是对软件设计中普遍存在(反复出现)的各种问题,所提出的解决方案。它并不直接用来完成代码的编写,而是描述在各种不同情况下,要怎么解决问题的一种方案。面向对象设计模式通常以类别或对象来描述其中的关系和相互作用,但不涉及用来完成应用程序的特定类别或对象。—— 维基百科

有三种模式:创建型模式,结构型模式、行为型模式。

  • 创建型模式:解决与创建对象相关的问题。
  • 结构型模式:处理实体之间的关系,以及它们如何共同组成一个更大的结构。
  • 行为型模式:处理对象如何相互通信和交互。

创建型设计模式

创建设计模式将创建对象,而不是直接实例化对象。

在软件工程中,创建型模式是处理对象创建的设计模式,试图根据实际情况使用合适的方式创建对象,因为基本的对象创建方式可能会导致设计上的问题,或增加设计的复杂度。创建型模式的关注点是如何创建对象,其核心思想是要把对象的创建和使用相分离。—— 维基百科

  • 工厂模式
  • 抽象工厂
  • 构建器模式
  • 原型模式
  • 单例模式

1. 工厂模式

工厂模式定义了一个用于创建单个对象的接口,并让子类决定要实例化类。

工厂方法模式(英语:Factory method pattern)是一种实现了“工厂”概念的面向对象设计模式。就像其他创建型模式一样,它也是处理在不指定对象具体类型的情况下创建对象的问题。工厂方法模式的实质是“定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类。—— 维基百科

实例

以一个点为例,有一个 Point 类,必须创建一个笛卡尔点和一个极点。将定义一个 Point 工厂来完成这项工作。

CoordinateSystem = {
    CARTESIAN:0,
    POLAR:1
};

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    static get factory() {
        return new PointFactory();
    }
}

现在将创建 Point 工厂,现在将使用工厂:

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    static get factory() {
        return new PointFactory();
    }
}
class PointFactory {
    static newCartesianPoint(x, y) {
        return new Point(x, y);
    }

    static newPolarPoint(rho, theta) {
        return new Point(rho * Math.cos(theta), rho * Math.sin(theta));
    }
}
const point = PointFactory.newPolarPoint(5, Math.PI / 2);
const point2 = PointFactory.newCartesianPoint(5, 6);
console.log(point);
console.log(point2);

2. 抽象工厂

抽象工厂创建公共对象的族或组,而不指定它们的具体类。

抽象工厂模式提供了一种方式,可以将一组具有同一主题的单独的工厂封装起来。—— 维基百科

实例

将使用饮料和饮料制造机的示例。

class Drink {
    consume() {}
}
class Tea extends Drink {
    consume() {
        console.log("This is tea");
    }
}
class Coffee extends Drink {
    consume() {
        console.log("This is coffee");
    }
}
class DrinkFactory {
    prepare(amount) {}
}
class TeaFactory extends DrinkFactory {
    makeTea() {
        console.log("Tea Created");
        return new Tea();
    }
}
class CoffeeFactory extends DrinkFactory {
    makeCoffee() {
        console.log("Coffee Created");
        return new Coffee();
    }
}
const teaDrinkFactory = new TeaFactory();
const tea = teaDrinkFactory.makeTea();
tea.consume();
const coffeeDrinkFactory = new CoffeeFactory();
const coffee = coffeeDrinkFactory.makeCoffee();
coffee.consume();

3. 构建器模式

构建器模式从简单对象构造复杂对象。

又名:建造模式,是一种对象构建模式。它可以将复杂对象的建造过程抽象出来(抽象类别),使这个抽象过程的不同实现方法可以构造出不同表现(属性)的对象。—— 维基百科

实例

将使用存储 Person 信息的 person 类的 ab 示例。

class Person {
    constructor() {
        this.streetAddress = this.postcode = this.city = "";
        this.companyName = this.position = "";
        this.annualIncome = 0;
    }

    toString() {
        return `个人生活在 ${this.streetAddress},${this.city},${this.postcode} ,工作在 ${this.companyName} 作为一名 ${this.position} 收入 ${this.annualIncome}`;
    }
}

现在将创建 Person BuilderPerson Job Builder 和 Person Address Builder

class PersonBuilder {
    constructor(person = new Person()) {
        this.person = person;
    }

    get lives() {
        return new PersonAddressBuilder(this.person);
    }

    get works() {
        return new PersonJobBuilder(this.person);
    }
    build() {
        return this.person;
    }
}
class PersonJobBuilder extends PersonBuilder {
    constructor(person) {
        super(person);
    }
    at(companyName) {
        this.person.companyName = companyName;
        return this;
    }
    asA(position) {
        this.person.position = position;
        return this;
    }
    earning(annualIncome) {
        this.person.annualIncome = annualIncome;
        return this;
    }
}

class PersonAddressBuilder extends PersonBuilder {
    constructor(person) {
        super(person);
    }

    at(streetAddress) {
        this.person.streetAddress = streetAddress;
        return this;
    }

    withPostcode(postcode) {
        this.person.postcode = postcode;
        return this;
    }

    in(city) {
        this.person.city = city;
        return this;
    }
}

现在将使用上面定义的构建器:

const personBuilder = new PersonBuilder();
const person = personBuilder.lives
    .at("高新南九道")
    .in("深圳")
    .withPostcode("518029")
    .works.at("字节跳动")
    .asA("工程师")
    .earning(10000)
    .build();
console.log(person.toString()); // 个人生活在 高新南九道,深圳,518029 ,工作在 字节跳动 作为一名 工程师 收入 10000

4. 原型模式

原型模式从现有对象创建新对象。

其特点在于通过“复制”一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的“原型”,这个原型是可定制的。—— 维基百科

实例

使用汽车的例子:

class Car {
    constructor(name, model) {
        this.name = name;
        this.model = model;
    }
    setName(name) {
        console.log(name);
        this.name = name;
    }
    clone() {
        return new Car(this.name, this.model);
    }
}
const car = new Car();
car.setName("闪电");

const car2 = car.clone();
car2.setName("麦昆");

5. 单例模式

单例模式确保只为特定类创建一个对象。

在软件工程中,单例模式是一种软件设计模式,它将类的实例化限制为一个“单一”实例。当需要一个对象来协调整个系统的动作时,这很有用。 —— 维基百科

实例

创建一个单例类:

class Singleton {
    constructor() {
        const instance = this.constructor.instance;
        if (instance) {
            return instance;
        }
        this.constructor.instance = this;
    }

    say() {
        console.log("Saying……");
    }
}
const s1 = new Singleton();
const s2 = new Singleton();
console.log("Are they same?" + (s1 === s2));
s1.say();

到此这篇关于结合 ES6 类编写JavaScript 创建型模式的文章就介绍到这了,更多相关JS 创建型模式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • js实现炫酷的烟花效果

    js实现炫酷的烟花效果

    这篇文章主要为大家详细介绍了js实现炫酷的烟花效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-09-09
  • BootstrapTable refresh 方法使用实例简单介绍

    BootstrapTable refresh 方法使用实例简单介绍

    本文就bootstrapTable refresh 方法如何传递参数做简单举例说明,非常不错,具有参考借鉴价值,需要的朋友参考下吧
    2017-02-02
  • 详解ECMAScript2019/ES10新属性

    详解ECMAScript2019/ES10新属性

    这篇文章主要介绍了详解ECMAScript2019/ES10新属性,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • JS跨域解决方案之使用CORS实现跨域

    JS跨域解决方案之使用CORS实现跨域

    正常使用AJAX会需要正常考虑跨域问题,所以伟大的程序员们又折腾出了一系列跨域问题的解决方案,如JSONP、flash、ifame、xhr2等等。本文给大家介绍JS跨域解决方案之使用CORS实现跨域,感兴趣的朋友参考下吧
    2016-04-04
  • js 数组去重的四种实用方法

    js 数组去重的四种实用方法

    怎样去掉Javascript的Array的重复项,这个问题看起来简单,但考的不仅仅是实现这个功能,更能看出你对计算机程序执行的深入理解
    2014-09-09
  • 给事件响应函数传参数的四种方式小结

    给事件响应函数传参数的四种方式小结

    这篇文章主要介绍了给事件响应函数传参数的四种方式。需要的朋友可以过来参考下,希望对大家有所帮助
    2013-12-12
  • javascript实现行拖动的方法

    javascript实现行拖动的方法

    这篇文章主要介绍了javascript实现行拖动的方法,涉及javascript鼠标事件及页面元素的相关操作技巧,需要的朋友可以参考下
    2015-05-05
  • JavaScript中的动态 import()用法示例解析

    JavaScript中的动态 import()用法示例解析

    这篇文章主要为大家介绍了JavaScript中的动态import()用法示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-04-04
  • 详解微信小程序-扫一扫 wx.scanCode() 扫码大变身

    详解微信小程序-扫一扫 wx.scanCode() 扫码大变身

    这篇文章主要介绍了微信小程序-扫一扫wx.scanCode() 扫码大变身,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04
  • input点击后placeholder中的提示消息消失

    input点击后placeholder中的提示消息消失

    placeholder属性是HTML5 中为input添加的。在input上提供一个占位符,文字形式展示输入字段预期值的提示信息(hint),该字段会在输入为空时显示
    2016-01-01

最新评论