工厂模式

#DesignPattern

Review

  1. 2023-12-09 18:23

一、Introduction #

工厂模式(Factory Pattern)是一种创建模式,它提供用于创建对象的接口,但允许子类更改将创建的对象的类型。 它封装了对象创建过程,使其更加灵活并与客户端代码解耦。

// Product class
class Product {
  constructor(name) {
    this.name = name;
  }
}

// Factory for creating products
class ProductFactory {
  createProduct(name) {
    return new Product(name);
  }
}

// Usage
const factory = new ProductFactory();
const productA = factory.createProduct('Product A');
const productB = factory.createProduct('Product B');

console.log(productA.name); // Output: 'Product A'
console.log(productB.name); // Output: 'Product B'

Abstract Factory Pattern

// Abstract Product classes
class Button {
  render() {}
}

class Checkbox {
  render() {}
}

// Concrete Product classes
class MacButton extends Button {
  render() {
    return 'Render Mac button';
  }
}

class MacCheckbox extends Checkbox {
  render() {
    return 'Render Mac checkbox';
  }
}

class WindowsButton extends Button {
  render() {
    return 'Render Windows button';
  }
}

class WindowsCheckbox extends Checkbox {
  render() {
    return 'Render Windows checkbox';
  }
}

// Abstract Factory interface
class GUIFactory {
  createButton() {}
  createCheckbox() {}
}

// Concrete Factories
class MacFactory extends GUIFactory {
  createButton() {
    return new MacButton();
  }

  createCheckbox() {
    return new MacCheckbox();
  }
}

class WindowsFactory extends GUIFactory {
  createButton() {
    return new WindowsButton();
  }

  createCheckbox() {
    return new WindowsCheckbox();
  }
}

// Usage
function createUI(factory) {
  const button = factory.createButton();
  const checkbox = factory.createCheckbox();

  return { button, checkbox };
}

const macUI = createUI(new MacFactory());
console.log(macUI.button.render()); // Output: 'Render Mac button'
console.log(macUI.checkbox.render()); // Output: 'Render Mac checkbox'

const windowsUI = createUI(new WindowsFactory());
console.log(windowsUI.button.render()); // Output: 'Render Windows button'
console.log(windowsUI.checkbox.render()); // Output: 'Render Windows checkbox'

When to Use Which Pattern #

  • Use the Factory Pattern when you want to encapsulate the object creation process and provide a simple interface for creating objects with different implementations.
  • Use the Abstract Factory Pattern when you need to create families of related or dependent objects that must work together. It helps ensure that the created objects are compatible and cohesive.

Reference #