返回
揭秘 JavaScript 设计模式:点亮编程新视野
前端
2024-01-15 06:21:39
1. 创意设计模式
1.1 单例模式
单例模式是一种确保某个类只有一个实例并提供该实例的访问权限的模式。它广泛用于需要全局访问的对象(如应用程序配置或数据库连接)中。
示例:
class Singleton {
private static instance;
constructor() {
if (!Singleton.instance) {
Singleton.instance = this;
}
return Singleton.instance;
}
// 其它方法...
}
const singleton = new Singleton();
console.log(singleton === new Singleton()); // true
1.2 工厂方法模式
工厂方法模式是一种创建对象的模式,其中工厂决定要创建的具体类,从而将对象的创建和使用分离,使代码更具灵活性。
示例:
class ShapeFactory {
createShape(type) {
switch (type) {
case "circle":
return new Circle();
case "square":
return new Square();
default:
throw new Error("Invalid shape type");
}
}
}
class Circle {
draw() {
console.log("Drawing a circle");
}
}
class Square {
draw() {
console.log("Drawing a square");
}
}
const factory = new ShapeFactory();
const circle = factory.createShape("circle");
const square = factory.createShape("square");
circle.draw(); // Drawing a circle
square.draw(); // Drawing a square
1.3 抽象工厂模式
抽象工厂模式是一种创建一系列相关或依赖对象的模式,其中工厂方法决定要创建的具体产品类,从而将产品的创建和使用分离,使代码更具灵活性。
示例:
class AbstractFactory {
createProductA() {
throw new Error("Abstract method not implemented");
}
createProductB() {
throw new Error("Abstract method not implemented");
}
}
class ConcreteFactory1 extends AbstractFactory {
createProductA() {
return new ProductA1();
}
createProductB() {
return new ProductB1();
}
}
class ConcreteFactory2 extends AbstractFactory {
createProductA() {
return new ProductA2();
}
createProductB() {
return new ProductB2();
}
}
class ProductA {
doSomething() {
console.log("Product A do something");
}
}
class ProductB {
doSomething() {
console.log("Product B do something");
}
}
class ProductA1 extends ProductA {
// Override doSomething()
}
class ProductA2 extends ProductA {
// Override doSomething()
}
class ProductB1 extends ProductB {
// Override doSomething()
}
class ProductB2 extends ProductB {
// Override doSomething()
}
const factory1 = new ConcreteFactory1();
const productA1 = factory1.createProductA();
const productB1 = factory1.createProductB();
productA1.doSomething(); // Product A1 do something
productB1.doSomething(); // Product B1 do something
const factory2 = new ConcreteFactory2();
const productA2 = factory2.createProductA();
const productB2 = factory2.createProductB();
productA2.doSomething(); // Product A2 do something
productB2.doSomething(); // Product B2 do something
1.4 建造者模式
建造者模式是一种创建复杂对象的模式,其中建造者类负责一步一步地构建对象,而客户端代码只需指定要创建的对象类型,即可获得最终的对象。
示例:
class CarBuilder {
private car;
constructor() {
this.car = new Car();
}
buildEngine() {
this.car.engine = "V8";
}
buildBody() {
this.car.body = "Coupe";
}
buildWheels() {
this.car.wheels = [
"Front left",
"Front right",
"Rear left",
"Rear right",
];
}
getResult() {
return this.car;
}
}
class Car {
engine;
body;
wheels;
}
const builder = new CarBuilder();
builder.buildEngine();
builder.buildBody();
builder.buildWheels();
const car = builder.getResult();
console.log(car);
1.5 原型模式
原型模式是一种创建对象的模式,其中新对象是通过复制现有对象(原型对象)创建的,从而可以快速创建具有相同属性和行为的新对象。
示例:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
clone() {
return new Person(this.name, this.age);
}
}
const person = new Person("John", 30);
const clone = person.clone();
console.log(person === clone); // false
console.log(person.name === clone.name); // true
console.log(person.age === clone.age); // true
2. 结构设计模式
2.1 适配器模式
适配器模式是一种将一个类的接口转换成另一个接口,以便两个本来不兼容的类可以一起工作。
示例:
class LegacyCalculator {
add(a, b) {
return a + b;
}
}
class NewCalculator {
sum(a, b) {
return a + b;
}
}
class CalculatorAdapter {
constructor(legacyCalculator) {
this.legacyCalculator = legacyCalculator;
}
sum(a, b) {
return this.legacyCalculator.add(a, b);
}
}
const legacyCalculator = new LegacyCalculator();
const adapter = new CalculatorAdapter(legacyCalculator);
const result = adapter.sum(1, 2);
console.log(result); // 3
2.2 装饰模式
装饰模式是一种向现有对象添加新功能而无需修改其原有结构的模式。
示例:
class Shape {
draw() {
console.log("Drawing a shape");
}
}
class Circle extends Shape {
draw() {
super.draw();
console.log("Drawing a circle");
}
}
class ColoredShapeDecorator extends Shape {
constructor(shape) {
super();
this.shape = shape;
}
draw() {
this.shape.draw();
console.log("Coloring the shape");
}
}
const circle = new Circle();
const coloredCircle = new ColoredShapeDecorator(circle);
coloredCircle.draw();
2.3 立面图模式
立面图模式是一种为一组相关的类提供一个统一的接口,使客户端代码只需与这个统一的接口交互,而无需了解底层类的细节。
示例:
class Order {
constructor(id, items) {
this.id = id;
this.items = items;
}
getTotalPrice() {
return this.items.reduce((acc, item) => acc + item.price, 0);
}
}
class OrderProcessor {
processOrder(order) {
// Validate the order
if (!order.id || order.items.length === 0) {
throw new Error("Invalid order");
}
// Calculate the total price
const totalPrice = order.getTotalPrice();
// Create an invoice
const invoice = new Invoice(order.id, totalPrice);
// Send the invoice to the customer
console.log(`Invoice sent to customer for order ${order.id}`);
// Ship the order
console.log(`Order ${order.id} shipped`);
}
}
const order = new Order(1, [
{ id: 1, name: "Product A", price: 10 },
{ id: 2, name: "Product B", price: 15 },
]);
const orderProcessor = new OrderProcessor();
orderProcessor.processOrder(order);