js实现模式
实现单例模式
单例模式确保一个类只有一个实例,并提供全局访问点。在JavaScript中,可以利用闭包或模块化实现。
const Singleton = (function() {
let instance;
function createInstance() {
return {
// 单例对象的方法和属性
showMessage: function() {
console.log("Hello Singleton");
}
};
}
return {
getInstance: function() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
// 使用示例
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true
实现观察者模式
观察者模式定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖它的对象都会得到通知。
class Subject {
constructor() {
this.observers = [];
}
subscribe(observer) {
this.observers.push(observer);
}
unsubscribe(observer) {
this.observers = this.observers.filter(obs => obs !== observer);
}
notify(data) {
this.observers.forEach(observer => observer.update(data));
}
}
class Observer {
update(data) {
console.log(`Observer received data: ${data}`);
}
}
// 使用示例
const subject = new Subject();
const observer1 = new Observer();
const observer2 = new Observer();
subject.subscribe(observer1);
subject.subscribe(observer2);
subject.notify("Hello Observers");
实现工厂模式
工厂模式定义一个用于创建对象的接口,让子类决定实例化哪一个类。
class Product {
constructor(name) {
this.name = name;
}
}
class Factory {
createProduct(type) {
switch(type) {
case 'A':
return new Product('Product A');
case 'B':
return new Product('Product B');
default:
throw new Error('Unknown product type');
}
}
}
// 使用示例
const factory = new Factory();
const productA = factory.createProduct('A');
const productB = factory.createProduct('B');
console.log(productA.name); // Product A
console.log(productB.name); // Product B
实现策略模式
策略模式定义一系列算法,将每个算法封装起来,并使它们可以互相替换。
class Strategy {
execute(a, b) {
throw new Error('This method must be implemented');
}
}
class AddStrategy extends Strategy {
execute(a, b) {
return a + b;
}
}
class SubtractStrategy extends Strategy {
execute(a, b) {
return a - b;
}
}
class Context {
constructor(strategy) {
this.strategy = strategy;
}
setStrategy(strategy) {
this.strategy = strategy;
}
executeStrategy(a, b) {
return this.strategy.execute(a, b);
}
}
// 使用示例
const context = new Context(new AddStrategy());
console.log(context.executeStrategy(5, 3)); // 8
context.setStrategy(new SubtractStrategy());
console.log(context.executeStrategy(5, 3)); // 2
实现装饰器模式
装饰器模式动态地给一个对象添加一些额外的职责,相比继承更加灵活。
class Coffee {
cost() {
return 5;
}
}
class MilkDecorator {
constructor(coffee) {
this.coffee = coffee;
}
cost() {
return this.coffee.cost() + 2;
}
}
class SugarDecorator {
constructor(coffee) {
this.coffee = coffee;
}
cost() {
return this.coffee.cost() + 1;
}
}
// 使用示例
let coffee = new Coffee();
console.log(coffee.cost()); // 5
coffee = new MilkDecorator(coffee);
console.log(coffee.cost()); // 7
coffee = new SugarDecorator(coffee);
console.log(coffee.cost()); // 8
实现代理模式
代理模式为其他对象提供一种代理以控制对这个对象的访问。

class RealImage {
constructor(filename) {
this.filename = filename;
this.loadFromDisk();
}
loadFromDisk() {
console.log(`Loading image: ${this.filename}`);
}
display() {
console.log(`Displaying image: ${this.filename}`);
}
}
class ProxyImage {
constructor(filename) {
this.filename = filename;
this.realImage = null;
}
display() {
if (!this.realImage) {
this.realImage = new RealImage(this.filename);
}
this.realImage.display();
}
}
// 使用示例
const image = new ProxyImage("test.jpg");
image.display(); // 首次调用会加载并显示
image.display(); // 直接显示,不再加载






