一句话总结JS的设计模式

工厂模式

new一个创建者来批量生产商品

class Product {
	constructor (name) {
		this.name = name
	}
	init() {
		alert('init')
	}
	fun1() {
		alert('fun1')
	}
	fun2() {
		alert('fun2')
	}
}

class Creator {
	create(name) {
		return new Product(name)
	}
}

// 测试
let creator = new Creator()
let p = creator.create('p1')
p.fun1()
复制代码

单例模式

如果没有创建过,就创建。否则就使用之前new的,保证只有一个实例

class SingleObject {
	login() {
		console.log('login');
	}
}


SingleObject.getInstance = (function(){
	let instance
	return function () {
		if (!instance) {
			instance = new SingleObject()
		} 
		return instance
	}
})()

let obj1 = SingleObject.getInstance()
obj1.login()

let obj2 = SingleObject.getInstance()
obj2.login()

console.log('是否是单例模式', obj1 === obj2);

let obj3 = new SingleObject()
obj3.login()


console.log('是否是单例模式', obj1 === obj3);
复制代码

适配器模式

重点在转换方法

class Adaptee {
	specificRequest() {
		return '德国标准插头'
	}
}

class Target {
	constructor() {
		this.adaptee = new Adaptee()
	}
	request() {
		let info = this.adaptee.specificRequest();
		return `${info} - 转换器 - 中国标准插头`
	}
}

// 测试
let target = new Target()
let res = target.request()

console.log(res);
复制代码

装饰器模式

在不影响原来功能的基础上添加新的功能

function log(target, name, descriptor) {
	// body...
	let oldValue = descriptor.value
	descriptor.value = function() {
		console.log(`calling ${name}`, arguments)
		return oldValue.apply(this, arguments)
	}
	return descriptor
}
class Math {
	@log
	add (a, b) {
		return a+b
	}
}

let math = new Math()
const result = math.add(2, 4)
console.log('result', result)
复制代码

观察者模式

一边设置,一边触发

// 观察者模式
// 主题, 保存状态,状态变化子后出发所有观察者对象
class Subject {
    constructor(state) {
        this.state = state
        this.obervers = []
    }
    setState(state) {
        this.state = state
        this.notifyAllObervers()
    }
    getState() {
        return this.state
    }
    notifyAllObervers() {
        this.obervers.forEach(oberver => oberver.update())
    }
    attach(oberver) {
        this.obervers.push(oberver)
    }
}

class Oberver {
    constructor(name, subject) {
        this.name = name
        this.subject = subject
        this.subject.attach(this)
    }
    update() {
        console.log(`${this.name} update, state: ${this.subject.getState()}`)
    }
}
// 初始化一个主题
let subject = new Subject();
// 
let o1 = new Oberver('o1', subject);
let o2 = new Oberver('o2', subject);
let o3 = new Oberver('o3', subject);
subject.setState(2)
复制代码

迭代器模式

各种数组,都能遍历

class Interator {
    constructor(container) {
        this.container = container
        this.index = 0
    }
    next() {
        if (this.hasNaxt()) {
            console.log(this.container.list[this.index]);
            this.index ++
        }
    }
    hasNaxt() {
        if (this.index === this.container.list.length) {
            return false
        }
        return true
    }
}

class Container {
    constructor(list) {
        this.list = list
    }
    interator() {
        return new Interator(this)
    }
}

let container = new Container([1, 2, 3, 4, 5]);
let interator = container.interator()
while (interator.hasNaxt()) {
    interator.next()
}

复制代码

状态模式

红绿黄灯切换处理

class State {
    constructor(color) {
        this.color = color
    }
    handleState(context) {
        context.setState(this.color)
        console.log(`turn to ${this.color}`);
    }
}

class Context {
    constructor() {
        this.state = null
    }
    getState() {
        return this.state
    }
    setState(state) {
        this.state = state
    }
}
let context = new Context()
let green = new State('green')
let red = new State('red')
let yellow = new State('yellow')

green.handleState(context)
red.handleState(context)
yellow.handleState(context)
复制代码

原型模式

重点在Object.create(prototype)

const prototype = {
    getName: function () {
       return this.firstName + '-' + this.lastName
    },
    say: function () {
        alert('hello')
    }
}

// 基于原型创建x
let x = Object.create(prototype)
x.firstName = 'M'
x.lastName = 'A'
alert(x.getName())
x.say()

// 基于原型创建b
let b = Object.create(prototype)
b.firstName = 'B'
b.lastName = 'A'
alert(b.getName())
b.say()

复制代码

桥接模式

三角形、圆形。红色、黄色。组合处理

class Color  {
    constructor(color) {
        this.color = color
    }
}

class Shape  {
    constructor(name, color) {
        this.name = name
        this.color = color
    }
    draw() {
        console.log(`${this.color.color}, ${this.name}`);
    }
}
let red = new Color('red')
let yellow = new Color('yellow')

let sjx = new Shape('三角形', red)
sjx.draw()

let yx = new Shape('原型', yellow)
yx.draw()
复制代码

策略模式

分类进行

class normalUser {
    buy() {
        console.log('普通用户购买')
    }
}

class memberUser {
    buy() {
        console.log('会员用户购买')
    }
}

class vipUser {
    buy() {
        console.log('VIP 用户购买')
    }
}

let u1 = new normalUser()
u1.buy()
let m1 = new memberUser()
m1.buy()
let v1 = new vipUser()
v1.buy()
复制代码

命令模式

将军发送命令给小号手,小号手传送命令给士兵

// 接收者
class Receiver {
    exec() {
        console.log("执行")
    }
}
// 命令者
class Command {
    constructor(receiver) {
        this.receiver = receiver
    }
    cmd () {
        console.log('执行命令')
        this.receiver.exec()
    }
}
// 触发者
class Invoker {
    constructor(command) {
        this.command = command
    }
    invoker() {
        console.log('开始')
        this.command.cmd()
    }
}

let solider = new Receiver()
let trumper = new Command(solider)
let general = new Invoker(trumper)
general.invoker()
复制代码

备忘录模式

返回、再返回

class Memento {
    constructor(content) {
        this.content = content
    }
    getContent() {
        return this.content
    }
}

// 备忘列表
class CareTaker {
    constructor() {
        this.list = []
    }
    add(memento) {
        this.list.push(memento)
    }
    get(index) {
        return this.list[index]
    }
}

// 编辑器
class Editor {
    constructor() {
        this.content = null
    }
    setContent(content) {
        this.content = content
    }
    getContent() {
        return this.content
    }
    saveContentToMemento() {
        return new Memento(this.content)
    }
    getContentFromMemento(memento) {
        this.content = memento.getContent()
    }
}

// 测试代码
let editor = new Editor()
let careTaker = new CareTaker()

editor.setContent('111')
editor.setContent('222')
careTaker.add(editor.saveContentToMemento())
editor.setContent('333')
careTaker.add(editor.saveContentToMemento())
editor.setContent('444')

console.log(editor.getContent())
editor.getContentFromMemento(careTaker.get(1))
editor.getContentFromMemento(careTaker.get(0))
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值