Technology Sharing

Summary of Software Design Patterns

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Design patterns are general solutions to common problems in software design. Here are some common design patterns, divided into three categories: creational patterns, structural patterns, and behavioral patterns.

Creational Patterns

These patterns provide mechanisms for object creation, increasing the flexibility and reusability of existing code.

  1. Singleton

    • Make sure a class has only one instance and provide a global access point.
  2. Factory Method

    • Define an interface for creating objects and let subclasses decide which class to instantiate.
  3. Abstract Factory

    • Create families of related or dependent objects without explicitly specifying the concrete classes.
  4. Builder

    • Builds a complex object and allows step-by-step construction.
  5. Prototype

    • Create a new instance by copying an existing instance, rather than creating a new one.

Structural Patterns

These patterns deal with object composition, or objects and the relationships between them.

  1. Adapter

    • Allows interface incompatibilities between objects to be resolved through an "adapter".
  2. Decorator pattern

    • Dynamically add additional responsibilities to an object.
  3. Proxy

    • Provides a substitute or placeholder for another object to control access to it.
  4. Facade

    • Provides a unified high-level interface for accessing a group of interfaces in a subsystem.
  5. Bridge Mode

    • Separate the abstraction from its implementation so that they can vary independently.
  6. Composite

    • Group objects into tree structures to represent part-whole hierarchies.
  7. Flyweight

    • Efficiently support large numbers of fine-grained objects through sharing.

Behavioral Patterns

These patterns focus on communication between objects, that is, how objects interact with each other and how responsibilities are distributed.

  1. Strategy

    • Define a set of algorithms, encapsulate them one by one, and make them interchangeable.
  2. Template Method

    • Define the skeleton of the algorithm in the method and defer its implementation to subclasses.
  3. Observer

    • A one-to-many dependency relationship between objects. When an object changes its state, all objects that depend on it will be notified and automatically updated.
  4. Iterator

    • Sequentially access the elements of an aggregate object without exposing its internal representation.
  5. Chain of Responsibility

    • This allows multiple objects to have a chance to process a request, thus avoiding coupling between the sender and receiver of the request.
  6. Command

    • Encapsulates the request as an object, allowing the user to parameterize the client with different requests.
  7. Memento

    • Capture the internal state of an object and save it outside the object without violating encapsulation.
  8. State

    • Allows an object to change its behavior when its internal state changes.
  9. Visitor pattern

    • Add new capabilities to an object structure (such as a composite structure).
  10. Mediator

    • Define a mediator object to simplify the interaction between original objects.
  11. Interpreter

    • Define a grammatical representation for a language and interpret sentences defined in that language.

During my last interview, I was asked to implement the subscription-publisher pattern with code. I have time to simulate these design patterns with js code.

For example

class PubSub {
  constructor() {
    this.events = {}; // 存储事件名称和对应的订阅者回调函数数组
  }

  // 订阅事件
  subscribe(event, callback) {
    if (!this.events[event]) {
      this.events[event] = []; // 如果事件不存在,初始化一个空数组
    }
    this.events[event].push(callback); // 将回调函数添加到订阅者的数组
  }

  // 取消订阅事件
  unsubscribe(event, callback) {
    if (!this.events[event]) {
      return;
    }
    this.events[event] = this.events[event].filter(cb => cb !== callback); // 移除指定的回调函数
  }

  // 取消特定事件的所有订阅
  unsubscribeAll(event) {
    if (this.events[event]) {
      delete this.events[event]; // 删除所有订阅者
    }
  }

  // 触发事件,使用 emit 作为方法名
  emit(event, data) {
    if (this.events[event]) {
      // 执行所有订阅者的回调函数
      this.events[event].forEach(callback => callback(data));
    }
  }

  // 检查是否有订阅者
  hasSubscribers(event) {
    return this.events[event] && this.events[event].length > 0;
  }
}

// 使用示例
const eventCenter = new PubSub();

// 订阅 'message' 事件
eventCenter.subscribe('message', (data) => {
  console.log(`Message received: ${data}`);
});

// 订阅 'greet' 事件
eventCenter.subscribe('greet', (name) => {
  console.log(`Hello, ${name}!`);
});

// 触发 'message' 事件
eventCenter.emit('message', 'Hello, Pub/Sub!');

// 触发 'greet' 事件
eventCenter.emit('greet', 'World');

// 取消对 'message' 事件的订阅
const myCallback = (data) => {
  console.log(`My callback received: ${data}`);
};
eventCenter.subscribe('message', myCallback);
eventCenter.unsubscribe('message', myCallback);

// 再次触发 'message' 事件,myCallback 不会被调用
eventCenter.emit('message', 'This message will not be received by myCallback');
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70

In this example,PubSub The class provides the following functionality:

  • subscribe The method allows a subscriber to register a callback function to a specific event.
  • unsubscribe Method allows a subscriber to unregister its callback function from a specific event.
  • unsubscribeAll Method cancels all subscriptions to a specific event.
  • emit The method triggers an event and executes the callback functions of all subscribers.
  • hasSubscribers Method checks if there are any subscribers for a specific event.