js设计模式

news/2024/4/27 13:41:30
  1. 单例模式
    它确保一个类只有一个实例,并提供了一个全局访问点来访问该实例。
class User {static #instance: User;#name: string;constructor(name: string) {this.#name = nameif (new.target !== User) {return}if (!User.#instance) {User.#instance = thisreturn User.#instance} else {// 提示console.error("不能重复初始化")}return User.#instance}get getName() {return this.#name}}const u1 = new User("张三")
const u2 = new User("李四")
console.log(u1 === u2); // true
console.log(u2.getName); // 张三

  1. 工厂模式
    它在创建对象时提供了一种封装机制,将实际创建对象的代码与使用代码分离
abstract class Shape {abstract draw(): void;
}class Rectangle implements Shape {draw() {console.log("draw rectangle")}
}
class Square implements Shape {draw() {console.log("draw square")}
}
class Circle implements Shape {draw() {console.log("draw circle ")}
}class ShapeFactory {public getShape(shapeType: "Rectangle" | "Square" | "Circle"): Shape {switch (shapeType) {case "Rectangle":return new Rectangle();case "Square":return new Square();case "Circle":return new Circle();default:throw new Error("没有这个形状")}}
}const shapeFactory = new ShapeFactory()
const rectangle = shapeFactory.getShape("Rectangle")
const square = shapeFactory.getShape("Square")
const circle = shapeFactory.getShape("Circle")
rectangle.draw() // draw rectangle
square.draw() // draw square
circle.draw() // draw circle

  1. 原型模式
    复用原型上的方法和属性以提高性能
const shapePrototype = {name: "",draw: function () {console.log(this.name);}
};const shape1 = Object.create(shapePrototype, {name: {value: "square"}
});
const shape2 = Object.create(shapePrototype, {name: {value: "circle"}
});shape1.draw() // square
shape2.draw() // circle
console.log(shape1.draw === shape2.draw) // true

采用ES6的class是同样的效果

class Shape {name: stringconstructor(name: string) {this.name = name}draw(): void {console.log(this.name)}
}const shape1 = new Shape("square")
const shape2 = new Shape("circle")shape1.draw() // square
shape2.draw() // circle
console.log(shape1.draw === shape2.draw) // true

  1. 适配器模式
    可用来在现有接口和不兼容的类之间进行适配。它被添加到现有代码中来协调两个不同的接口
class NewAPI {newGetList() {return [1, 2, 3]}
}class OldAPI {oldGetList() {return [2, 3, 4]}
}class APIAdapter extends OldAPI {constructor() { super() }newGetList() {return this.oldGetList()}
}function getList(api: NewAPI) {return api.newGetList()
}getList(new NewAPI())
getList(new APIAdapter())
getList(new OldAPI())  // 报错
  1. 依赖注入模式
    将一个对象所依赖的其他对象的创建过程,从该对象本身中分离出来,以便更好地实现解耦和可测试性。
// 定义一个容器类
class Container {bindings: { [key: string]: Function };constructor() {this.bindings = {};}bind(abstract: string, concrete: Function) {this.bindings[abstract] = concrete;}make(abstract: string | number) {const concretion = this.bindings[abstract];if (typeof concretion === 'function') {console.log(this)return concretion(this);}return concretion;}
}// 创建容器实例
const container = new Container();// 绑定服务到容器
container.bind('logger', () => {return {log(message: any) {console.log(message);}};
});// 使用依赖注入
function serviceWithDependency(container: Container) {const logger = container.make('logger');logger.log('This is a dependency injection example.');
}// 解析依赖并执行函数
serviceWithDependency(container);

采用装饰器模式

import "reflect-metadata"const requiredMetadataKey = Symbol("required");function required(target: Object, propertyKey: string | symbol, parameterIndex: number) {let existingRequiredParameters: number[] = Reflect.getOwnMetadata(requiredMetadataKey, target, propertyKey) || [];existingRequiredParameters.push(parameterIndex);Reflect.defineMetadata(requiredMetadataKey, existingRequiredParameters, target, propertyKey);
}function validate(target: any, propertyName: string, descriptor: TypedPropertyDescriptor<Function>) {let method = descriptor.value!;descriptor.value = function () {let requiredParameters: number[] = Reflect.getOwnMetadata(requiredMetadataKey, target, propertyName);console.log(propertyName)if (requiredParameters) {for (let parameterIndex of requiredParameters) {if (parameterIndex >= arguments.length || arguments[parameterIndex] === undefined) {throw new Error("Missing required argument.");}}}return method.apply(this, arguments);};
}class BugReport {type = "report";title: string;constructor(title: string) {this.title = title;}@validateprint(@required verbose: boolean) {if (verbose) {console.log(`type: ${this.type}\ntitle: ${this.title}`)return;} else {console.log(`title: ${this.title}`)}}@validatelog(@required log: string) {console.log(log)}
}const bugReport = new BugReport("test")
bugReport.print(true)
bugReport.log("this is a example")

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.cpky.cn/p/11061.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

链动2+1模式 完全合法合规 不存在传销问题!!

在商业经营中&#xff0c;营销策略的巧妙运用对于提升产品销量和扩大品牌影响力至关重要。然而&#xff0c;企业在制定和执行营销策略时&#xff0c;必须严格遵循法律法规&#xff0c;以免陷入法律风险。本文将着重探讨链动21模式的法律要素&#xff0c;以论证其合规性。 一、链…

npm i安装依赖报错,但是cnpm i 却安装成功

问题描述&#xff1a;在a项目中npm i 安装依赖时发生以上报错&#xff0c;但是cnpm i 却成功&#xff0c;而且在其他项目中npm i 安装其他项目依赖也能成功.... 解决办法&#xff1a;删除项目中package-lock.json文件后再npm i 即可

Redis入门到实战-第三弹

Redis入门到实战 Redis数据类型官网地址Redis概述Redis数据类型介绍更新计划 Redis数据类型 官网地址 声明: 由于操作系统, 版本更新等原因, 文章所列内容不一定100%复现, 还要以官方信息为准 https://redis.io/Redis概述 Redis是一个开源的&#xff08;采用BSD许可证&#…

nodejs+vue高校门诊管理系统python-flask-django-php

相比于以前的传统手工管理方式&#xff0c;智能化的管理方式可以大幅降低高校门诊的运营人员成本&#xff0c;实现了高校门诊管理的标准化、制度化、程序化的管理&#xff0c;有效地防止了高校门诊管理的随意管理&#xff0c;提高了信息的处理速度和精确度&#xff0c;能够及时…

AV1:帧内预测(一)

​VP9支持10种帧内预测模式&#xff0c;包括8种角度模式和非角度模式DC、TM(True Motion)模式&#xff0c;AV1在其基础上进一步扩展&#xff0c;AV1帧内预测角度模式更细化&#xff0c;同时新增了部分非角度模式。 扩展的角度模式 AV1在VP9角度模式的基础上进一步扩展&#xf…

4G/5G视频记录仪_联发科MTK6765平台智能记录仪方案

视频记录仪主板采用了联发科MT6765芯片&#xff0c;该芯片采用12nm FinFET制程工艺&#xff0c;8*Cortex-A53架构&#xff0c;搭载安卓11.0/13.0系统&#xff0c;主频最高达2.3GHz&#xff0c;待机功耗可低至5ma&#xff0c;并具有快速数据传输能力。配备了2.4英寸高清触摸显示…