JavaScript 面向对象-设计模式
1️⃣ 创建型模式
1. 单例模式(Singleton)
保证一个类只有一个实例,并提供全局访问点。
js
class Singleton {
constructor(name) {
if (Singleton.instance) {
return Singleton.instance
}
this.name = name
Singleton.instance = this
}
getName() {
return this.name
}
}
const a = new Singleton("Alice")
const b = new Singleton("Bob")
console.log(a === b) // true
console.log(b.getName()) // 'Alice'✅ ES6 特性:class、静态属性/单例缓存
2. 工厂模式(Factory)
根据条件创建不同对象,封装实例化逻辑。
js
class Dog {
speak() {
console.log("Woof!")
}
}
class Cat {
speak() {
console.log("Meow!")
}
}
class AnimalFactory {
static createAnimal(type) {
switch (type) {
case "dog":
return new Dog()
case "cat":
return new Cat()
default:
throw new Error("Unknown animal type")
}
}
}
const dog = AnimalFactory.createAnimal("dog")
dog.speak() // Woof!✅ ES6 特性:static 方法、class
3. 建造者模式(Builder)
分步构建复杂对象,隐藏内部实现。
js
class Car {
constructor() {
this.parts = []
}
addPart(part) {
this.parts.push(part)
return this // 链式调用
}
show() {
console.log(this.parts.join(", "))
}
}
const car = new Car().addPart("Engine").addPart("Wheel").addPart("Seat")
car.show() // Engine, Wheel, Seat✅ ES6 特性:链式调用、类
2️⃣ 结构型模式
1. 装饰器模式(Decorator)
动态给对象添加功能。
js
class Coffee {
cost() {
return 5
}
}
class MilkDecorator {
constructor(coffee) {
this.coffee = coffee
}
cost() {
return this.coffee.cost() + 2
}
}
const coffee = new Coffee()
const milkCoffee = new MilkDecorator(coffee)
console.log(milkCoffee.cost()) // 7✅ ES6 特性:class、组合
2. 代理模式(Proxy)
控制对象访问(可用于权限控制、缓存等)。
js
const user = {
name: "Alice",
age: 20,
}
const proxyUser = new Proxy(user, {
get(target, prop) {
console.log(`Getting ${prop}`)
return target[prop]
},
set(target, prop, value) {
console.log(`Setting ${prop} to ${value}`)
target[prop] = value
return true
},
})
proxyUser.name // Getting name
proxyUser.age = 21 // Setting age to 21✅ ES6 特性:Proxy
3️⃣ 行为型模式
1. 观察者模式(Observer)
对象状态改变时,通知所有依赖者。
js
class Subject {
constructor() {
this.observers = []
}
subscribe(observer) {
this.observers.push(observer)
}
notify(data) {
this.observers.forEach(obs => obs.update(data))
}
}
class Observer {
constructor(name) {
this.name = name
}
update(data) {
console.log(`${this.name} received: ${data}`)
}
}
const sub = new Subject()
sub.subscribe(new Observer("A"))
sub.subscribe(new Observer("B"))
sub.notify("Hello Observers")
// A received: Hello Observers
// B received: Hello Observers✅ ES6 特性:class、箭头函数
2. 策略模式(Strategy)
把算法封装成对象,可动态切换。
js
class Payment {
constructor(strategy) {
this.strategy = strategy
}
pay(amount) {
this.strategy.pay(amount)
}
}
class AliPay {
pay(amount) {
console.log(`Paid ${amount} with Alipay`)
}
}
class WeChatPay {
pay(amount) {
console.log(`Paid ${amount} with WeChat`)
}
}
const payment = new Payment(new AliPay())
payment.pay(100) // Paid 100 with Alipay
payment.strategy = new WeChatPay()
payment.pay(200) // Paid 200 with WeChat