JavaScript 设计模式:理解创建型设计模式
2023-11-14 15:39:14
设计模式:创建型模式
在软件开发中,设计模式提供了一个统一的框架,用于解决常见的软件工程问题。创建型设计模式专注于优化和灵活的对象创建机制。本文将深入探讨一些常用的创建型设计模式及其在 JavaScript 中的应用。
1. 简单工厂模式
简单工厂模式又称静态工厂方法或工厂函数。它使用一个工厂对象(函数)来创建一系列相似的产品对象实例。通过调用该函数,可以返回对应的对象实例。例如,在体育用品商店购买体育器材时,只需要告诉售货员所需的器材名称,售货员就会帮我们找到并介绍对应的产品。
代码示例:
function createProduct(type) {
switch (type) {
case 'basketball':
return new Basketball();
case 'soccer ball':
return new SoccerBall();
default:
return null;
}
}
2. 工厂方法模式
工厂方法模式将创建对象的过程委托给不同的子类,每个子类负责创建其自己的特定产品类型。与简单工厂模式不同,工厂方法模式允许开发者在不修改客户端代码的情况下扩展产品类型。
代码示例:
class ProductFactory {
createProduct(type) {
throw new Error('Abstract method not implemented');
}
}
class BasketballFactory extends ProductFactory {
createProduct() {
return new Basketball();
}
}
3. 抽象工厂模式
抽象工厂模式提供了一种创建一系列相关或依赖产品的接口,这些产品属于同一产品家族。抽象工厂模式允许开发者一次性创建一组相关的产品,而无需指定它们的具体类。
代码示例:
class ProductA {
operationA() {
throw new Error('Abstract method not implemented');
}
}
class ProductB {
operationB() {
throw new Error('Abstract method not implemented');
}
}
class ConcreteProductA1 extends ProductA {
operationA() {
// Specific implementation
}
}
class ConcreteProductB1 extends ProductB {
operationB() {
// Specific implementation
}
}
class AbstractFactory {
createProductA() {
throw new Error('Abstract method not implemented');
}
createProductB() {
throw new Error('Abstract method not implemented');
}
}
class ConcreteFactory1 extends AbstractFactory {
createProductA() {
return new ConcreteProductA1();
}
createProductB() {
return new ConcreteProductB1();
}
}
4. 建造者模式
建造者模式分离对象的构建和表示。该模式允许开发者使用不同的构建步骤灵活地创建复杂的对象,而无需关心对象的内部细节。
代码示例:
class Product {
constructor() {
this.parts = [];
}
addPart(part) {
this.parts.push(part);
}
}
class ProductBuilder {
constructor() {
this.product = new Product();
}
buildPartA() {
// Specific implementation
}
buildPartB() {
// Specific implementation
}
getProduct() {
return this.product;
}
}
const builder = new ProductBuilder();
builder.buildPartA();
builder.buildPartB();
const product = builder.getProduct();
5. 原型模式
原型模式通过克隆现有对象实例来创建新对象。该模式避免了创建新对象时昂贵的构造过程,特别适合创建大量相同或相似对象的场景。
代码示例:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
clone() {
return new Person(this.name, this.age);
}
}
const person1 = new Person('John', 30);
const person2 = person1.clone();
6. 单例模式
单例模式确保整个应用程序中只有一个特定类的实例存在。该模式用于创建全局对象或资源,在需要共享状态或控制对象创建时非常有用。
代码示例:
class Singleton {
static getInstance() {
if (!this.instance) {
this.instance = new Singleton();
}
return this.instance;
}
}
const singleton = Singleton.getInstance();
常见问题解答
1. 什么时候应该使用简单工厂模式?
当需要创建一系列相似的产品,并且产品类型很少发生变化时。
2. 工厂方法模式和简单工厂模式有什么区别?
工厂方法模式允许在不修改客户端代码的情况下扩展产品类型,而简单工厂模式不允许。
3. 什么时候应该使用抽象工厂模式?
当需要创建一系列相关的或依赖的产品时,这些产品属于同一产品家族。
4. 建造者模式和工厂方法模式有什么相似之处?
它们都是用于创建对象的模式,但是建造者模式更适用于创建复杂的对象,而工厂方法模式更适用于创建简单或中等复杂度的对象。
5. 单例模式有什么优点?
单例模式可以确保整个应用程序中只有一个特定类的实例,这可以帮助控制资源和防止冲突。