当前位置: 首页 > news >正文

基本设计模式

  • 单例模式
    ES5
function Duck1(name:string){this.name=namethis.instance=null
}Duck1.prototype.getName=function(){console.log(this.name)
}Duck1.getInstance=function(name:string){if(!this.instance){this.instance= new Duck1(name)}
}
const a=Duck1.getInstance('a')
const b=Duck1.getInstance('b')console.log(a===b) // true

ES6

class Duck{name="xxx"static instance:any=nullaction(){console.log('123')}static getInstance(){if(!this.instance){this.instance=new Duck()} return this.instance}
}const obj1=Duck.getInstance()
const obj2=Duck.getInstance()console.log(obj1===obj2) // true
  • 工厂模式
class Duck{name="xxx"constructor(name:string){this.name=name}   
}function factory(name:string){return new Duck(name)
}const a=factory('x')
const b=factory('s')
  • 策略模式
    代码里有多个if的情况时,做成策略模式,好处:
    策略模式利用组合,委托等技术和思想,有效的避免很多if条件语句
    策略模式提供了开放-封闭原则,使代码更容易理解和扩展
    策略模式中的代码可以复用
    策略模式优化的例子
    `
  • 代理模式
class Duck{name="xxx"constructor(name:string){this.name=name}   getName(){console.log('name: ',this.name)}setName(newValue:string){this.name=newValue}
}const tp=new Duck('a')const obj = new Proxy(tp,{set:function(target,property,value){return Reflect.set(target,property,'new:'+value)},get(target,property){if(property==='getName'){return function(value:String){Reflect.get(target,property,'new:'+value)}}return Reflect.get(target,property)}
})console.log(obj.name)obj.setName('jack')console.log(obj.name)

输出:
请添加图片描述

http://www.lryc.cn/news/311478.html

相关文章:

  • 双通道音频功率放大电路,外接元件少, 通道分离性好,3V 的低压下可正常使用——D2025
  • Linux 内核获取函数size
  • Python+neo4j构建豆瓣电影知识图谱
  • DolphinScheduler——介绍及架构设计
  • 【Python】约瑟夫环问题
  • Python成功解决AttributeError: ‘Series‘ object has no attribute ‘set_value‘
  • 基于springboot+vue的医院药品管理系统
  • Python爬虫——Urllib库-1
  • 瑞_Redis_短信登录(一)
  • 《剑指 Offer》专项突破版 - 面试题 70 : 排序数组中只出现一次的数字(C++ 实现)
  • Linux安全加固功能
  • 最新AI系统ChatGPT网站H5系统源码,支持Midjourney绘画
  • 【服务器数据恢复】昆腾存储中raid5磁盘阵列数据恢复案例
  • 企业微信变更主体怎么改?
  • 常用生理眼电信号整理合集 (EOG)
  • 【场景题】让你设计一个订单号生成服务,该怎么做?
  • 使用GraphView实现简单的绘图工具
  • javaWebssh教师荣誉库管理系统myeclipse开发mysql数据库MVC模式java编程计算机网页设计
  • Android minigbm框架普法
  • 01、MongoDB -- 下载、安装、配置文件等配置 及 副本集配置
  • uniapp中导入css和scss的区别
  • RabbitMQ-TTL/死信队列/延迟队列高级特性
  • docker安装php7.4安装(swoole)
  • 身份证识别系统(安卓)
  • Python教程——最后一波来喽
  • 学生管理系统(python实现)
  • Java读取文件
  • 曾桂华:车载座舱音频体验探究与思考| 演讲嘉宾公布
  • 面试题HTML+CSS+网络+浏览器篇
  • wordpress外贸独立站