基本设计模式

  • 单例模式
    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. 设计模式基本名词

    2024-03-10 20:36:05       11 阅读
  2. 设计模式的7大基本原则

    2024-03-10 20:36:05       30 阅读
  3. 设计模式的六大基本原则

    2024-03-10 20:36:05       16 阅读
  4. 设计模式的7大基本原则

    2024-03-10 20:36:05       17 阅读
  5. 设计模式有哪些基本原则

    2024-03-10 20:36:05       11 阅读
  6. 设计模式-23种基础模式目录

    2024-03-10 20:36:05       10 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-10 20:36:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-10 20:36:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-10 20:36:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-10 20:36:05       18 阅读

热门阅读

  1. MySQL的页与行格式

    2024-03-10 20:36:05       27 阅读
  2. DPN网络

    DPN网络

    2024-03-10 20:36:05      21 阅读
  3. 银行app软件使用技巧,避免被限制非柜面交易。

    2024-03-10 20:36:05       55 阅读
  4. 初识C语言—字符串、转义字符、注释

    2024-03-10 20:36:05       22 阅读
  5. vue3注册全局组件

    2024-03-10 20:36:05       18 阅读
  6. Docker Register 搭建私有镜像仓库

    2024-03-10 20:36:05       20 阅读
  7. Linux 系统上卸载 Docker

    2024-03-10 20:36:05       21 阅读
  8. 在 Docker 环境下安装 OpenWrt

    2024-03-10 20:36:05       25 阅读
  9. Docker修改网段

    2024-03-10 20:36:05       22 阅读
  10. Kotlin 中的数据类

    2024-03-10 20:36:05       21 阅读