设计模式在 TypeScript 中的应用 - 单例模式
定义
只有一个实例,并提供全局访问。
实现
思路:用一个变量来标识当前是否已经为某个类创建过对象,如果是,则在下一次获取该类的实例时,直接返回之前创建的对象,否则返回新对象。
饿汉模式
特点:类加载时就初始化。
class Singleton {
private static instance = new Singleton()
// 将 constructor 设为私有属性,防止 new 调用
private constructor () {}
static getInstance (): Singleton {
return Singleton.instance
}
}
const singleton1 = Singleton.getInstance()
const singleton2 = Singleton.getInstance()
console.log(singleton1 === singleton2) // true
懒汉模式
特点:需要时才创建对象实例。
class Singleton {
private static instance: Singleton
private constructor () {}
static getInstance (): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton()
}
return this.instance
}
}
const singleton1 = Singleton.getInstance()
const singleton2 = Singleton.getInstance()
console.log(singleton1 === singleton2) // true
简单栗子
class Singleton {
private constructor (name: string, age: number) {
this.name = name
this.age = age
}
private static instance: Singleton
public name: string
public age: number
static getInstance (
name: string,
age: number
): Singleton {
if (!this.instance) {
this.instance = new Singleton(name, age)
}
return this.instance
}
}
const singleton1 = Singleton.getInstance('Mary', 20)
const singleton2 = Singleton.getInstance('Jack', 20)
console.log(singleton1, singleton2)
漫漫长路
前端之路
推荐阅读
巧用 TypeScript(五)---- infer
在这个条件语句 T extends (param: infer P) => any ? P : T 中,infer P 表示待推断的函数参数。
三毛赞 47阅读 17.5k评论 4
vue-property-decorator使用手册
@Component 装饰器可以接收一个对象作为参数,可以在对象中声明 components ,filters,directives等未提供装饰器的选项,也可以声明computed,watch等
似曾相识赞 17阅读 29.1k评论 7
2022大前端总结和2023就业分析
我在年前给掘金平台分享了《2022年热点技术盘点》的前端热点,算是系统性的梳理了一下我自己对前端一整年的总结。年后,在知乎上看到《前端的就业行情怎么样?》,下面都是各种唱衰前端的论调,什么裁员,外包化...
i5ting赞 14阅读 652评论 3
JS 函数式概念: 管道 和 组合
微信搜索 【大迁世界】, 我会第一时间和你分享前端行业趋势,学习途径等等。本文 GitHub [链接] 已收录,有一线大厂面试完整考点、资料以及我的系列文章。
前端小智赞 8阅读 737
Vue3 + Vite2 + TypeScript + Pinia(Vuex)+JSX 搭建企业级开发脚手架【开箱即用】
随着Vue3的普及,已经有越来越多的项目开始使用Vue3。为了快速进入开发状态,在这里向大家推荐一套开箱即用的企业级开发脚手架,框架使用:Vue3 + Vite2 + TypeScript + JSX + Pinia(Vuex) + Antd。废话不多话,...
阳晨@赞 11阅读 3.2k
快速构建页面结构的 3D Visualization
可以通过 控制台 --> 右边的三个小点 --> More Tools --> Layers 打开。即可以看到页面的一个 3D 层级关系,像是这样:
chokcoco赞 6阅读 1.6k
表格集算表高性能原理——怎样实现纯前端百万行数据秒级响应
集算表 (Table Sheet)是一个具备高性能渲染、数据绑定功能、公式计算能力的数据表格,通过全新构建的关系型数据管理器结合结构化公式,在高性能表格的基础上提供排序、筛选、样式、行列冻结、自动更新、单元格...
葡萄城技术团队赞 4阅读 15.3k
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。