基本设计模式

  • 单例模式
    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)

输出:

相关推荐
终端鹿4 分钟前
Pinia 与 Vue Router 权限控制实战(衔接Pinia基础篇)
前端·javascript·vue.js
绝世唐门三哥28 分钟前
React--- 状态更新:何时需要拷贝,何时不需要?
javascript·react.js·ecmascript
我叫黑大帅34 分钟前
JS中的两大定时器
前端·javascript·面试
掘金安东尼41 分钟前
⏰前端周刊第 458 期v2026.3.24
前端·javascript·面试
张元清1 小时前
useMediaQuery:React 响应式设计完全指南
前端·javascript·面试
小金鱼Y1 小时前
一文吃透 JavaScript 防抖:从原理到实战,让你的页面不再 “手抖”
前端·javascript·面试
紫_龙1 小时前
最新版vue3+TypeScript开发入门到实战教程之Vue3详解props
前端·vue.js·typescript
孟陬1 小时前
为什么国外技术大神都爱自己搭博客,而国内程序员却挤在微信公众号或掘金?
java·typescript·前端框架
进击的尘埃2 小时前
Nginx 反向代理 WebSocket 和 SSE 的踩坑
javascript
进击的尘埃2 小时前
IndexedDB实战:浏览器端离线存储与同步方案
javascript