基本设计模式

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

输出:

相关推荐
芳草萋萋鹦鹉洲哦1 小时前
【vue/js】文字超长悬停显示的几种方式
前端·javascript·vue.js
开发者小天2 小时前
React中的 闭包陷阱
前端·javascript·react.js
涔溪2 小时前
Vue3 的核心语法
前端·vue.js·typescript
国服第二切图仔2 小时前
Electron for 鸿蒙pc项目实战之tab标签页组件
javascript·electron·harmonyos·鸿蒙pc
Neptune13 小时前
深入浅出:理解js的‘万物皆对象’与原型链
前端·javascript
阿迷不想上班3 小时前
windows自动任务定期执行
javascript
盗德3 小时前
最全音频处理WaveSurfer.js配置文档
前端·javascript
Heo3 小时前
关于Gulp,你学这些就够了
前端·javascript·面试
祈澈菇凉3 小时前
Next.js 零基础开发博客后台管理系统教程(八):提升用户体验 - 表单状态、加载与基础验证
前端·javascript·ux