代理模式(structural 7)

208 阅读1分钟

2.3 代理模式(proxy)

  • 对一些对象提供代理,以限制那些对象去访问其它对象。
function Car() {
	this.drive = function () {
		return 'driving'
	}
}

function CarProxy(driver) {
	this.driver = driver
	this.drive = function () {
		if (driver.age < 18) return 'too young to drive'
		return new Car().drive()
	}
}

function Driver(age) {
	this.age = age
}

module.exports = [Car, CarProxy, Driver]
const expect = require('chai').expect
const [Car, CarProxy, Driver] = require('../src/structural/proxy/proxy')

describe('代理模式测试', () => {
	it('驾驶', () => {
		var driver = new Driver(20)
		var kid = new Driver(16)

		var car = new CarProxy(driver)
		expect(car.drive()).to.equal('driving')

		car = new CarProxy(kid)
		expect(car.drive()).to.equal('too young to drive')
	})
})

es6 实现

class Car {
	drive() {
		return 'driving'
	}
}

class CarProxy {
	constructor(driver) {
		this.driver = driver
	}
	drive() {
		return this.driver.age < 18 ? 'too young to drive' : new Car().drive()
	}
}

class Driver {
	constructor(age) {
		this.age = age
	}
}

export { Car, CarProxy, Driver }
const expect = require('chai').expect
import { Car, CarProxy, Driver } from '../src/structural/proxy/proxy_es6'

describe('代理模式 es6测试', () => {
	it('驾驶', () => {
		let driver = new Driver(28)
		let kid = new Driver(10)

		let car = new CarProxy(driver)
		expect(car.drive()).to.equal('driving')

		car = new CarProxy(kid)
		expect(car.drive()).to.equal('too young to drive')
	})
})