创建型模式
约 638 字大约 2 分钟
设计模式创建型模式
2026-04-14
概述
创建型模式关注对象的创建过程,将对象的创建与使用分离,从而提供更大的灵活性和可维护性。
模式分类
| 模式 | 描述 |
|---|---|
| 单例模式 | 确保只有一个实例 |
| 工厂方法模式 | 定义创建对象的接口 |
| 抽象工厂模式 | 创建一系列相关对象 |
| 建造者模式 | 一步一步构建复杂对象 |
| 原型模式 | 通过复制现有对象创建 |
单例模式 (Singleton)
确保一个类只有一个实例,并提供一个全局访问点。
class Singleton {
static #instance = null;
static getInstance() {
if (!Singleton.#instance) {
Singleton.#instance = new Singleton();
}
return Singleton.#instance;
}
constructor() {
if (Singleton.#instance) {
return Singleton.#instance;
}
}
}
const s1 = Singleton.getInstance();
const s2 = Singleton.getInstance();
console.log(s1 === s2); // true应用场景
- 数据库连接池
- 全局配置管理器
- 日志记录器
工厂方法模式 (Factory Method)
定义一个创建对象的接口,让子类决定实例化哪个类。
class Factory {
create(type) {
switch (type) {
case 'A': return new ProductA();
case 'B': return new ProductB();
default: throw new Error('Unknown type');
}
}
}
// 使用
const factory = new Factory();
const productA = factory.create('A');应用场景
- 对象创建逻辑比较复杂
- 需要根据配置动态创建对象
抽象工厂模式 (Abstract Factory)
提供一个创建一系列相关对象的接口,而不需要指定它们的具体类。
class AbstractFactory {
createProductA() {}
createProductB() {}
}
class ConcreteFactory1 extends AbstractFactory {
createProductA() { return new ProductA1(); }
createProductB() { return new ProductB1(); }
}
class ConcreteFactory2 extends AbstractFactory {
createProductA() { return new ProductA2(); }
createProductB() { return new ProductB2(); }
}应用场景
- 需要创建一系列相关对象
- 系统要由多个产品系列中的一个来配置
建造者模式 (Builder)
将一个复杂对象的构建与它的表示分离。
class Builder {
constructor() {
this.reset();
}
reset() {
this.product = new Product();
}
buildPartA() {
this.product.parts.push('A');
return this;
}
buildPartB() {
this.product.parts.push('B');
return this;
}
getResult() {
return this.product;
}
}
// 使用
const result = new Builder()
.buildPartA()
.buildPartB()
.getResult();应用场景
- 构造函数参数过多
- 创建过程需要分步骤完成
原型模式 (Prototype)
通过复制现有对象来创建新对象。
class Prototype {
constructor() {
this.name = 'default';
}
clone() {
return Object.create(this);
}
}
// 使用
const proto = new Prototype();
const clone = proto.clone();应用场景
- 对象创建成本较高
- 需要避免使用
new关键字
模式对比
| 模式 | 关注点 | 复杂度 | 适用场景 |
|---|---|---|---|
| 单例 | 实例数量 | 低 | 全局唯一 |
| 工厂方法 | 对象创建 | 中 | 逻辑较复杂 |
| 抽象工厂 | 产品系列 | 高 | 系列对象 |
| 建造者 | 构建步骤 | 中 | 复杂对象 |
| 原型 | 对象复制 | 低 | 高成本创建 |
