单例模式(Singleton Pattern):
单例模式确保一个类或对象只有一个实例,并使用全局变量来存储该实例。
示例代码:
javascriptclass Logger { constructor() { this.logs = []; } log(message) { this.logs.push(message); } } let instance = null; export function getInstance() { if (!instance) { // 创建单例 intance = new Logger(); } return intance; }
观察者模式(Observer Pattern):
观察者模式定义了一对多的依赖关系,当一个对象状态改变时,其所有依赖对象都会收到通知。
示例代码:
javascriptclass Subject { constructor() { this.observers = []; } addObserver(observer) { this.observers.push(observer); } notify(message) { this.observers.forEach((observer) => observer.update(message)); } } class Observer { update(message) { console.log(`Received message: ${message}`); } } // 使用观察者模式 const subject = new Subject(); const observer1 = new Observer(); const observer2 = new Observer(); subject.addObserver(observer1); subject.addObserver(observer2); subject.notify("Hello, observers!");
发布订阅者模式(Publish-Subscribe Pattern)
- 实现了松耦合,提供了关注点分离,允许发布者发布消息,订阅者接收消息,而不需要直接连接两个分离的系统。
- 示例代码:
javascript
class MessageBroker {
constructor() {
this.subscribers = {};
}
subscribe(topic, callback) {
if (!this.subscribers[topic]) {
this.subscribers[topic] = [];
}
this.subscribers[topic].push(callback);
}
publish(topic, message) {
if (this.subscribers[topic]) {
this.subscribers[topic].forEach((callback) => callback(message));
}
}
}
// 使用发布订阅者模式
const broker = new MessageBroker();
broker.subscribe("news", (message) => {
console.log(`Received news: ${message}`);
});
broker.publish("news", "New article published!");
// 输出:Received news: New article published!
工厂模式(Factory Pattern)
- 将对象的创建逻辑封装在工厂类中,客户端代码只需调用工厂方法即可获取所需对象。
- 隐藏了对象的具体实现细节,提高了代码的可维护性和可扩展性。
- 示例代码:
javascript
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} speaks`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} says Woof!`);
}
}
class Cat extends Animal {
speak() {
console.log(`${this.name} says Meow!`);
}
}
class AnimalFactory {
createAnimal(animalType, name) {
switch (animalType) {
case "dog":
return new Dog(name);
case "cat":
return new Cat(name);
default:
throw new Error("Invalid animal type");
}
}
}
// 使用工厂模式
const factory = new AnimalFactory();
const dog = factory.createAnimal("dog", "Buddy");
const cat = factory.createAnimal("cat", "Whiskers");
dog.speak(); // 输出:Buddy says Woof!
cat.speak(); // 输出:Whiskers says Meow!
策略模式(Strategy Pattern):
策略模式允许在运行时选择算法或行为,而不是在编译时固定。
示例代码:
javascriptclass PaymentStrategy { pay(amount) { throw new Error("This method must be overridden by subclasses."); } } class CreditCardPayment extends PaymentStrategy { pay(amount) { console.log(`Paid $${amount} using credit card.`); } } class PayPalPayment extends PaymentStrategy { pay(amount) { console.log(`Paid $${amount} using PayPal.`); } } // 使用策略模式 const paymentMethod = new CreditCardPayment(); paymentMethod.pay(100);
装饰器模式(Decorator Pattern):
装饰器模式允许在不修改现有对象的情况下动态地添加功能。
示例代码:
javascriptclass Coffee { cost() { return 5; } } class MilkDecorator { constructor(coffee) { this.coffee = coffee; } cost() { return this.coffee.cost() + 2; } } // 使用装饰器模式 const simpleCoffee = new Coffee(); const coffeeWithMilk = new MilkDecorator(simpleCoffee); console.log(`Cost of coffee with milk: $${coffeeWithMilk.cost()}`);
适配器模式(Adapter Pattern):
适配器模式用于将一个接口转换成另一个接口,以便不兼容的类可以一起工作。
示例代码:
javascriptclass OldApi { request() { return "Data from old API"; } } class NewApi { fetchData() { return "Data from new API"; } } class ApiAdapter { constructor(newApi) { this.newApi = newApi; } request() { return this.newApi.fetchData(); } } // 使用适配器模式 const newApi = new NewApi(); const adapter = new ApiAdapter(newApi); console.log(adapter.request());