基本设计模式

  • 单例模式
    ES5

    function Duck1(name:string){
    this.name=name
    this.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=null
    action(){
        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)

输出:

相关推荐
浮生望3 小时前
从作用域链到 React 陈旧闭包:为什么函数式更新能拿到最新 state
javascript
怕浪猫3 小时前
前端转全栈最低成本的技术栈选择
前端·javascript·面试
WebInfra4 小时前
Rsdoctor 2.0 发布:Agent 驱动的全自动优化工具
前端·javascript·node.js
濮水大叔4 小时前
CabloyJS 的 AI 时刻:从 TypeScript 全栈框架到 AI 规范驱动开发
typescript·ai编程·全栈
晨间晓4 小时前
图片到底偏什么颜色?用华为云码道开发 OpenCV 色彩偏移分析工具
javascript·opencv·华为云
智慧城市20304 小时前
关键供应商连续交付不合格批次,说明质量风险可能持续存在。企业需要建立“批次隔离、加严检验、驻厂遏制、复检放行、供应商升级”的处置闭环,同时统筹保供。
数据分析·策略模式·战略咨询·流程管理
鬼手点金12 小时前
nanoGPT/nanochat 能做出 DeepSeek/Qwen 这样的大模型吗?
服务器·前端·javascript·bug·openclaw
软件技术NINI13 小时前
美妆商城html+Css+js 4页
javascript·css·html
蛋蛋的就会顺顺的13 小时前
hot100 p0——栈,贪心算法,动态规划
java·前端·javascript·算法·leetcode·力扣
程序员Sunday13 小时前
TypeScript 的 any、unknown、never 有什么区别?
前端·面试·typescript