基本设计模式

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

输出:

相关推荐
机构师15 分钟前
<uniapp><指针组件>基于uniapp,编写一个自定义箭头指针组件
javascript·uni-app·vue·html
小桥风满袖17 分钟前
极简三分钟ES6 - 模块化
前端·javascript
new_daimond27 分钟前
设计模式-策略模式深度分析
设计模式·策略模式
bestadc1 小时前
LeetCode 几道 Promises 和 Time 的题目
javascript·算法·leetcode
萌萌哒草头将军2 小时前
Node.js v24.8.0 新功能预览!🚀🚀🚀
前端·javascript·node.js
辞去归来兮2 小时前
观察者模式 VS. 发布-订阅者模式
设计模式
太空游走的鱼2 小时前
Vue3 + Vite + Element Plus web转为 Electron 应用,解决无法登录、隐藏自定义导航栏
javascript·electron·vue3·管理系统·element plsu
Chris.Yuan7702 小时前
Java代理模式详解
java·开发语言·代理模式
GISer_Jing2 小时前
Next系统学习(二)
前端·javascript·node.js
织_网3 小时前
Electron 核心模块速查表
javascript·electron·策略模式