基本设计模式

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

输出:

相关推荐
一斤代码2 小时前
vue3 下载图片(标签内容可转图)
前端·javascript·vue
3Katrina3 小时前
深入理解 useLayoutEffect:解决 UI "闪烁"问题的利器
前端·javascript·面试
coderlin_4 小时前
BI布局拖拽 (1) 深入react-gird-layout源码
android·javascript·react.js
伍哥的传说4 小时前
React 实现五子棋人机对战小游戏
前端·javascript·react.js·前端框架·node.js·ecmascript·js
我在北京coding4 小时前
element el-table渲染二维对象数组
前端·javascript·vue.js
布兰妮甜4 小时前
Vue+ElementUI聊天室开发指南
前端·javascript·vue.js·elementui
SevgiliD4 小时前
el-button传入icon用法可能会出现的问题
前端·javascript·vue.js
我在北京coding4 小时前
Element-Plus-全局自动引入图标组件,无需每次import
前端·javascript·vue.js
鱼 空4 小时前
解决el-table右下角被挡住部分
javascript·vue.js·elementui
小李飞飞砖6 小时前
React Native 组件间通信方式详解
javascript·react native·react.js