基本设计模式

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

输出:

相关推荐
阿猫的故乡27 分钟前
Vue过渡动画从入门到装X:淡入淡出、滑动、列表动画、第三方库全搞定
前端·javascript·vue.js
小和尚敲木头1 小时前
vue3 vite动态拼接图片路径
javascript
艾利克斯冰1 小时前
Java 设计模式-行为型模式(更新中)
java·开发语言·设计模式
我叫黑大帅1 小时前
前端如何竖屏固定视口背景
前端·javascript·面试
不会敲代码12 小时前
我花了三天时间,终于把 Cookie、XSS、CSRF 和浏览器存储给整明白了
javascript·面试
贩卖黄昏的熊2 小时前
flex 布局快速梳理
开发语言·javascript·css3·html5
swipe2 小时前
Mem0 x Agent 实战系列:分层记忆 + 三路召回,搭建真正可用的长期记忆层
前端·javascript·面试
kyriewen2 小时前
手写 call、apply、bind:从原理到实现,附 3 个最容易忽略的边界情况
前端·javascript·面试
胡萝卜术3 小时前
从内存视角重新认识 JavaScript 数据类型:一份深度学习笔记
前端·javascript·面试
LiuJun2Son3 小时前
Angular 快速入门:从零搭建你的第一个应用
前端·javascript·angular.js