当前位置: 首页 > article >正文

【设计模式】01- 一文理解常用设计模式-“创建型模式”篇

一、前言

最近在复习设计模式,撰写、整理了内容和代码片段,和大家一起交流学习。

设计模式是软件设计中常见问题的典型解决方案。

二、模式分类

模式可以根据其意图或目的来分类。常见的设计模式包括:

  • 创建型模式提供创建对象的机制, 增加已有代码的灵活性和可复用性;

  • 结构型模式介绍如何将对象和类组装成较大的结构, 并同时保持结构的灵活和高效;

  • 行为型模式负责对象间的高效沟通和职责委派;

本篇文章介绍创建型模式,后续会更新其他两类设计模式。


三、创建型模式概述

创建型模式主要用于对象的创建过程,它隐藏了对象的创建逻辑,使得代码更具灵活性和可维护性。

四、常见创建型模式(配合代码)

1、单例模式(Singleton Pattern)

确保一个类只有一个实例,并提供一个全局访问点来访问这个实例。

// 单例模式示例
const Singleton = (function () {
       let instance;

       function createInstance() {
           const object = new Object({ name: 'Singleton Object' });
           return object;
       }

       return {
           getInstance: function () {
               if (!instance) {
                   instance = createInstance();
               }
               return instance;
           }
       };
   }());
   
   // 使用示例
   const instance1 = Singleton.getInstance();
   const instance2 = Singleton.getInstance();

   console.log(instance1 === instance2); // 输出: true

代码运行结果

2、工厂模式(Factory Pattern)

定义一个创建对象的接口,让子类决定实例化哪个类。工厂方法使一个类的实例化延迟到其子类。

解释:工厂模式就像一个工厂,根据不同的需求生产不同的产品。你只需要告诉工厂你需要什么,工厂就会帮你创建出来。

// 工厂模式示例
function CarFactory() {
    this.createCar = function (type) {
        let car;
        if (type === 'sedan') {
            car = new Sedan();
        } else if (type === 'suv') {
            car = new SUV();
        }
        car.drive = function () {
            console.log(`Driving a ${this.constructor.name}`);
        };
        return car;
    };
}
​
function Sedan() {
    this.type = 'Sedan';
}
​
function SUV() {
    this.type = 'SUV';
}
​
// 使用示例
const factory = new CarFactory();
const sedan = factory.createCar('sedan');
const suv = factory.createCar('suv');
​
sedan.drive(); // 输出: Driving a Sedan
suv.drive();   // 输出: Driving a SUV

代码运行结果

3、抽象工厂模式(Abstract Factory Pattern)

提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

简单理解:就像一个超级工厂,能生产不同品牌的汽车系列产品。

// 抽象工厂模式示例
// 抽象工厂
function AbstractCarFactory() {
    this.createEngine = function () {
        throw new Error('This method must be overridden!');
    };
    this.createWheel = function () {
        throw new Error('This method must be overridden!');
    };
}
​
// 具体工厂:丰田工厂
function ToyotaFactory() {
    AbstractCarFactory.call(this);
    this.createEngine = function () {
        return new ToyotaEngine();
    };
    this.createWheel = function () {
        return new ToyotaWheel();
    };
}
​
// 具体工厂:本田工厂
function HondaFactory() {
    AbstractCarFactory.call(this);
    this.createEngine = function () {
        return new HondaEngine();
    };
    this.createWheel = function () {
        return new HondaWheel();
    };
}
​
// 丰田发动机
function ToyotaEngine() {
    this.start = function () {
        console.log('Toyota engine started');
    };
}
​
// 丰田车轮
function ToyotaWheel() {
    this.rotate = function () {
        console.log('Toyota wheel rotating');
    };
}
// 本田发动机
function HondaEngine() {
    this.start = function () {
        console.log('Honda engine started');
    };
}
​
// 本田车轮
function HondaWheel() {
    this.rotate = function () {
        console.log('Honda wheel rotating');
    };
}
​
// 使用示例
const toyotaFactory = new ToyotaFactory();
const toyotaEngine = toyotaFactory.createEngine();
const toyotaWheel = toyotaFactory.createWheel();
​
toyotaEngine.start(); // 输出: Toyota engine started
toyotaWheel.rotate(); // 输出: Toyota wheel rotating
​
const hondaFactory = new HondaFactory();
const hondaEngine = hondaFactory.createEngine();
const hondaWheel = hondaFactory.createWheel();
​
hondaEngine.start(); // 输出: Honda engine started
hondaWheel.rotate(); // 输出: Honda wheel rotating
代码运行结果

4、建造者模式(Builder Pattern)

将一个复杂对象的构建与表示分离,使得同样的构建过程可以创建不同的表示。

简单理解:就像建造房子,有不同的建造步骤,最终可以建成不同风格的房子。

// 建造者模式示例
// 产品类:汽车
function Car() {
    this.wheels = null;
    this.engine = null;
    this.color = null;
​
    this.showInfo = function () {
        console.log(`Car with ${this.wheels} wheels, ${this.engine} engine and ${this.color} color`);
    };
}
​
// 建造者类
function CarBuilder() {
    this.car = new Car();
​
    this.setWheels = function (wheels) {
        this.car.wheels = wheels;
        return this;
    };
​
    this.setEngine = function (engine) {
        this.car.engine = engine;
        return this;
    };
​
    this.setColor = function (color) {
        this.car.color = color;
        return this;
    };
​
    this.build = function () {
        return this.car;
    };
}
​
// 使用示例
const builder = new CarBuilder();
const car = builder
   .setWheels(4)
   .setEngine('V8')
   .setColor('Red')
   .build();
​
car.showInfo(); // 输出: Car with 4 wheels, V8 engine and Red color

代码运行结果

 

5、原型模式(Prototype Pattern)

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

简单理解:就像复印文件,有一个原始文件作为模板,然后可以复印出很多份一样的文件。

// 原型模式示例
const carPrototype = {
    brand: 'Unknown',
    model: 'Unknown',
    start: function () {
        console.log(`Starting the ${this.brand} ${this.model}`);
    },
    clone: function () {
        const clone = Object.create(this);
        return clone;
    }
};
​
// 使用示例
const car1 = carPrototype.clone();
car1.brand = 'Toyota';
car1.model = 'Corolla';
​
const car2 = carPrototype.clone();
car2.brand = 'Honda';
car2.model = 'Civic';
​
car1.start(); // 输出: Starting the Toyota Corolla
car2.start(); // 输出: Starting the Honda Civic

代码运行结果


五、小结

设计模式在编程当中还是挺重要的,优点包括但不限于:代码复用性更高、可维护性更强、可扩展性更好。

有时间可以花点时间学习/复习一下,相信对我们的编程技术和编程思维会有很多进步~


http://www.kler.cn/a/543667.html

相关文章:

  • HCIA项目实践---网络层次常见的三种模型
  • 从肠道菌群到炎症因子:读懂疾病的预警信号
  • CEF132编译指南 MacOS 篇 - 构建 CEF (六)
  • Windows 系统 GDAL库 配置到 Qt 上
  • Visual Studio 进行单元测试【入门】
  • 在Uniapp中使用阿里云OSS插件实现文件上传
  • vue error Expected indentation of 2 spaces but found 4 indent
  • 好好说话:深度学习扫盲
  • 搜维尔科技在动作捕捉与动画制作、汽车制造与安全测试、机器人与自动化领域的一些案例
  • chromium-mojo
  • python 获取smpl身高 fbx身高
  • 数据仓库与数据挖掘记录 一
  • iOS主要知识点梳理回顾-3-运行时消息机制
  • leetcode 面试经典 150 题:跳跃游戏 II
  • NeRF与3D Gaussian的异同对比
  • MySQL 实战 4 种将数据同步到ES方案
  • kotlin标准库里面也有很多java类
  • 解锁大语言模型潜能:KITE 提示词框架全解析
  • 一区IEEE Trans|特征模态分解FMD,一维数据分解新方法-matlab免费代码
  • C#/.NET/.NET Core技术前沿周刊 | 第 24 期(2025年1.27-1.31)
  • PyCharm控制台中文乱码
  • MongoDB 的基本概念
  • 跟着李沐老师学习深度学习(八)
  • 计算机网络综合实训室解决方案(2025年最新版)
  • 使用 npx tailwindcss init 时发生 npm error could not determine executable to run 错误
  • FPGA 28 ,基于 Vivado Verilog 的呼吸灯效果设计与实现( 使用 Vivado Verilog 实现呼吸灯效果 )