es6 Mixin 模式的实现
2018-02-02 22:24
183 查看
Mixin 模式的实现
ES6 Mixin 指的是多个对象合成一个新的对象,新对象具有各个组成成员的接口。它的最简单实现如下。const a = {
a: 'a'
};
const b = {
b: 'b'
};
const c = {...a, ...b}; // {a: 'a', b: 'b'}
上面代码中,
c对象是
a对象和
b对象的合成,具有两者的接口。
下面是一个更完备的实现,将多个类的接口“混入”(mix in)另一个类。
function mix(...mixins) {
class Mix {}
for (let mixin of mixins) {
copyProperties(Mix, mixin); // 拷贝实例属性
copyProperties(Mix.prototype, mixin.prototype); // 拷贝原型属性
}
return Mix;
}
function copyProperties(target, source) {
for (let key of Reflect.ownKeys(source)) {
if ( key !== "constructor"
&& key !== "prototype"
&& key !== "name"
) {
let desc = Object.getOwnPropertyDescriptor(source, key);
Object.defineProperty(target, key, desc);
}
}
}
上面代码的
mix函数,可以将多个对象合成为一个类。使用的时候,只要继承这个类即可。
class DistributedEdit extends mix(Loggable, Serializable) {
// ...
}
相关文章推荐
- es6 使用修饰器实现Mixin模式
- es6 实例:使用Proxy实现观察者模式
- 什么是Mixin模式:带实现的协议
- 什么是Mixin模式:带实现的协议
- 什么是Mixin模式:带实现的协议
- 什么是Mixin模式:带实现的协议
- 观察者模式之ES6实现(一)
- 什么是Mixin模式:带实现的协议
- 利用ES6实现单例模式及其应用详解
- C++惯用法:奇特的递归模板模式(Curiously Recurring Template Pattern,CRTP,Mixin-from-above)
- 双机热备的实现模式 - 基于共享存储与纯软件方式
- Spring的单例模式底层实现学习笔记
- 设计模式C++实现(11)——装饰模式
- 策略模式的java样例实现(以鸭子为例)
- 使用模板方法模式实现可扩展性设计(Java示例)
- Android是否可以实现静默安装模式
- arc 模式下 使用宏定义单例模式(gcd 实现单例模式)
- Java之Builder模式(并用OC实现了这种模式)
- C#实现工厂模式简介--实现访问不同的数据库
- 如何实现C++单例模式?