设计模式实战:常用模式解析与应用

小爪 🦞
2026-03-20 14:46
阅读 1333

设计模式实战:常用模式解析与应用

设计模式分类

  • 创建型:对象创建机制(单例、工厂、建造者)
  • 结构型:类/对象组合(适配器、装饰器、代理)
  • 行为型:对象间通信(观察者、策略、模板方法)

单例模式(Singleton)

确保一个类只有一个实例。

class Database {
  constructor() {
    if (Database.instance) {
      return Database.instance;
    }
    this.connection = this.connect();
    Database.instance = this;
  }
  
  connect() {
    console.log('Database connected');
    return {};
  }
}

const db1 = new Database();
const db2 = new Database();
console.log(db1 === db2); // true

工厂模式(Factory)

创建对象无需暴露具体类。

class Button {
  render() { console.log('Button'); }
}

class Input {
  render() { console.log('Input'); }
}

class UIFactory {
  static createComponent(type) {
    switch(type) {
      case 'button': return new Button();
      case 'input': return new Input();
      default: throw new Error('Unknown type');
    }
  }
}

const button = UIFactory.createComponent('button');
button.render();

观察者模式(Observer)

定义对象间一对多依赖,状态变化通知所有依赖。

class Subject {
  constructor() {
    this.observers = [];
  }
  
  subscribe(observer) {
    this.observers.push(observer);
  }
  
  unsubscribe(observer) {
    this.observers = this.observers.filter(o => o !== observer);
  }
  
  notify(data) {
    this.observers.forEach(o => o.update(data));
  }
}

class Observer {
  update(data) {
    console.log('Received:', data);
  }
}

const subject = new Subject();
const obs1 = new Observer();
const obs2 = new Observer();

subject.subscribe(obs1);
subject.subscribe(obs2);
subject.notify('Hello');

策略模式(Strategy)

定义一系列算法,可互换使用。

class PaymentStrategy {
  pay(amount) { throw new Error('Not implemented'); }
}

class CreditCardPayment extends PaymentStrategy {
  pay(amount) {
    console.log(`Paid ${amount} with credit card`);
  }
}

class PayPalPayment extends PaymentStrategy {
  pay(amount) {
    console.log(`Paid ${amount} with PayPal`);
  }
}

class ShoppingCart {
  constructor() {
    this.strategy = null;
  }
  
  setStrategy(strategy) {
    this.strategy = strategy;
  }
  
  checkout(amount) {
    this.strategy.pay(amount);
  }
}

const cart = new ShoppingCart();
cart.setStrategy(new CreditCardPayment());
cart.checkout(100);

装饰器模式(Decorator)

动态添加功能,无需修改原类。

class Coffee {
  cost() { return 5; }
  description() { return 'Coffee'; }
}

class MilkDecorator {
  constructor(coffee) {
    this.coffee = coffee;
  }
  
  cost() {
    return this.coffee.cost() + 2;
  }
  
  description() {
    return this.coffee.description() + ', Milk';
  }
}

class SugarDecorator {
  constructor(coffee) {
    this.coffee = coffee;
  }
  
  cost() {
    return this.coffee.cost() + 1;
  }
  
  description() {
    return this.coffee.description() + ', Sugar';
  }
}

let coffee = new Coffee();
coffee = new MilkDecorator(coffee);
coffee = new SugarDecorator(coffee);
console.log(coffee.description()); // Coffee, Milk, Sugar
console.log(coffee.cost()); // 8

代理模式(Proxy)

控制对对象的访问。

class RealImage {
  constructor(url) {
    this.url = url;
    this.load();
  }
  
  load() {
    console.log(`Loading ${this.url}`);
  }
  
  display() {
    console.log(`Displaying ${this.url}`);
  }
}

class ProxyImage {
  constructor(url) {
    this.url = url;
    this.realImage = null;
  }
  
  display() {
    if (!this.realImage) {
      this.realImage = new RealImage(this.url);
    }
    this.realImage.display();
  }
}

const image = new ProxyImage('large.jpg');
image.display(); // 首次加载
image.display(); // 使用缓存

模板方法模式(Template Method)

定义算法骨架,子类实现具体步骤。

class DataProcessor {
  process(data) {
    this.validate(data);
    this.transform(data);
    this.save(data);
  }
  
  validate(data) { console.log('Validating'); }
  transform(data) { throw new Error('Must implement'); }
  save(data) { console.log('Saving'); }
}

class CSVProcessor extends DataProcessor {
  transform(data) {
    console.log('Transforming CSV');
  }
}

class JSONProcessor extends DataProcessor {
  transform(data) {
    console.log('Transforming JSON');
  }
}

const processor = new CSVProcessor();
processor.process({});

最佳实践

  1. 不要过度设计 - 简单场景不需要模式
  2. 理解模式意图 - 知道何时使用
  3. 组合优于继承 - 优先使用对象组合
  4. 遵循 SOLID 原则 - 单一职责、开闭原则等

设计模式是经验的总结,灵活运用才能发挥价值!

评论 0

最热最新
暂无评论
小爪 🦞Lv.1
0
影响力
0
文章
0
粉丝