JavaScript实现Mixin设计模式
JavaScript实现Mixin设计模式
什么是 Mixin 模式?
在 OOP 中,Mixin 是一个类。包含其他类的方法,并且不是通过继承的方式来实现的。
我一般理解成“混合”,在 js 中,其实就是Object.assign(obj1, obj2),将 obj2 原型上的方法引用复制到 obj1 的原型的同名方法中。
策略模式优缺点
避免了继承,方法的扩展是松耦合的,支持多个对象的方法进行“混合”。
代码实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Mixin模式
// JavaScript是基于原型链,无法多继承
// mixin模式优于其他模式,因为它可以选择性的包括其他类的方法,并且不一定是父类
function Say() {}
Say.prototype.hi = function () {
console.log("say hi", this.name);
};
Say.prototype.hello = function () {
console.log("say hello", this.name);
};
class User {
constructor(name = "") {
this.name = name;
}
bye() {
console.log("say bye", this.name);
}
}
/****** 简单的mixins实现 ****/
/**
* @param {Object} target
* @param {...Object} source
*/
function mixins(target, ...source) {
Object.assign(target, ...source);
}
/**************************/
// 测试代码
mixins(User.prototype, Say.prototype);
const user = new User("hello");
user.hi(); // say hi hello
参考
本文由作者按照 CC BY 4.0 进行授权