适配器模式(structural 1)

261 阅读1分钟

2.结构型模式(structural 7)

2.1 适配器模式(adapter)

  • 将一个类的接口转换成客户希望的另外一个接口。Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。
function Soldier(lvl) {
	this.lvl = lvl
}
//士兵攻击1
Soldier.prototype.attack = function () {
	return this.lvl * 1
}

function Jedi(lvl) {
	this.lvl = lvl
}
//用剑100
Jedi.prototype.attackWithSaber = function () {
	return this.lvl * 100
}

// 创建适配器 传入不同的对象 攻击不同
// 需要将Jedi的attackWithSaber 适配成 attack
function JediAdapter(jedi) {
	this.jedi = jedi
}

JediAdapter.prototype.attack = function () {
	return this.jedi.attackWithSaber()
}

module.exports = [Soldier, Jedi, JediAdapter]
const expect = require('chai').expect
const [Soldier, Jedi, JediAdapter] = require('../src/structural/adapter/adapter.js');

describe('适配器 测试', () => {
	it('攻击', () => {
		var stormrooper = new Soldier(1)
		var yoda = new JediAdapter(new Jedi(10))
		expect(yoda.attack()).to.equal(stormrooper.attack() * 1000)
	})
})

es6 实现

class Soldier {
	constructor(level) {
		this.level = level
	}

	attack() {
		return this.level * 1
	}
}

class Jedi {
	constructor(level) {
		this.level = level
	}

	attackWithSaber() {
		return this.level * 100
	}
}

class JediAdapter {
	constructor(jedi) {
		this.jedi = jedi
	}

	attack() {
		return this.jedi.attackWithSaber()
	}
}
export { Soldier, Jedi, JediAdapter }
const expect = require('chai').expect
import {
  Soldier,
  Jedi,
  JediAdapter
} from '../src/structural/adapter/adapter_es6';

describe('适配器 es6测试', () => {
	it('攻击', () => {
		var stormrooper = new Soldier(1)
		var yoda = new JediAdapter(new Jedi(10))
		expect(yoda.attack()).to.equal(stormrooper.attack() * 1000)
	})
})