设计模式(1)

92 阅读2分钟

1. 什么是设计模式

是为解决软件设计中通用问题而被提出的一套指导性思想。

2. 设计模式的好处

  • 让代码可以重复使用
  • 让代码稳定且易扩展
  • 可以提高代码的可读性

3. 设计模式需要遵循的原则

  1. 开闭原则(OCP)- 对拓展开放、对修改关闭

    目标:已有的场景下,对于需要拓展的功能进行开放、拒绝直接的破坏性功能修改

  2. 单一职责原则(SRP) - 通过解耦让每一个模块职责更加独立

    目标 - 一个功能模块只能做一件事

// sprint
// game store
class PUBGManager {
    openDialog() {
        // 弹框结算
        // 计算结算金额
        setPrice()
    }
}

const game = new PUBGManager()
game.openDialog() // 弹框 < = > 计算金额 两个维度相同的模块耦合

// 重构
// 业务前台
// gameManager.js - 业务
class PUBGManager {
    constructor(commanddd) {
        this.commanddd = commanddd
    }
    openDialog(price) {
        // 弹框结算
        commandLine.forEach((item) => {
            this.commanddd ? [item] && this.commanddd[item](price)
        })
    }
}

// 指令集 utils/commands.js
export {
    commandLine
}


// optManager.js - 底层仓库
class PriceManager {
    setPrice(price) {
        // 配置金额
    }
}

// main.js
const exe = new PriceManager()
const game1 = new PUBGManager(exe)
game1.openDialog(15)
  1. 依赖倒置原则(DIP)- 上层应用不应当依赖下层实现

    目标:面向抽象进行coding,而不是对实现进行coding,降低需求与实现的耦合

// code copied from yunyinTeacher
// sprint1
// 分享功能
class Store {
    constructor() {
        this.share = new Share()
    }
}

class Share {
    shareTo() {
        // 分享到不同的平台
    }
}

const store = new Store()
store.share.shareTo('wx')

// sprint2
// 评分功能
class Store {
    constructor() {
        this.share = new Share()
        this.rate = new Rate()
    }
}

class Share {
    shareTo() {
        // 分享到不同的平台
    }
}

class Rate {
    rate() {
        // 评分
    }
}

const store1 = new Store()
store1.rate.rate(5)

// 重构
// 目标:暴露挂载 => 动态挂载
class Store {
    // 维护模块名单
    static modules = new Map()

    constructor() {
        // 遍历当前的名单做初始化挂载
        for(let module of Store.modules.values()) {
            module.init(this)
        }
    }

    // 注入功能模块
    static inject(module) {
        Store.modules.set(module.constructor.name, module)
    }
}

class Rate {
    init(store) {
        store.rate = this
    }
    store(stars) {
        // 评分
    }
}

class Share {
    init(store) {
        store.share = this
    }
    shareTo(platform) {
        // 分享到不同平台
    }
}

// 依次注册完所有的模块
const rate = new Rate()
Store.inject(rate)

const share = new Share()
Store.inject(share)

const rate2 = new Rate()
Store.inject(rate2)

// 初始化商城
const store2 = new Store()
store2.rate.star(4)
  1. 接口隔离原则(ISP)

    目标:多个专业接口比单个数据量较大的接口要好用

  2. 里氏替换原则(LSP)

    目标:子类能够覆盖父类,父类能够出现的地方子类就能够出现