值代理
class Percentage {
constructor(percent) {
this.percent = percent;
}
toString() {
return `${this.percent}%`;
}
valueOf() {
return this.perect / 100;
}
}
let fivePercent = new Percentage(5);
console.log(fivePercent.toString()); // 5%
console.log(`100的5%是${100 * fivePercent}`); // 100的5%是5
属性代理
class Property {
constructor(value, name='') {
this._value = value;
this.name = name;
}
get value() {
return this._value;
}
set value(newValue) {
if(this._value === newValue) return;
console.log(`给${this.name}赋了一个新的值: ${newValue}`);
this._value = newValue;
}
}
class Creature {
constructor() {
this._agility = new Property(50, 'agility');
}
get agility() {
return this._agility.value;
}
set agility(value) {
this._agility.value = value;
}
}
let c = new Creature();
c.agility = 60;
c.agility = 70;
保护代理
class Car {
drive() {
console.log(`开车中...`);
}
}
class CarProxy {
constructor(driver){
this.driver = driver;
this._car = new Car();
}
drive() {
if (this.driver.age >= 18) {
this._car.driver();
} else {
console.log(`现在还太年经,还没有到驾驶的年龄...`);
}
}
}
class Driver {
constructor(age) {
this.age = age;
}
}
let car1 = new Car();
car1.drive(); // 开车中..
let car2 = new CarProxy(new Driver(15));
car2.drive(); // 现在还太年经,还没有到驾驶的年龄...
虚拟代理
class Image {
constructor(url) {
this.url = url;
console.log(`从${this.url}加载了图片...`);
}
draw() {
console.log(`从${this.url}绘制了图片...`);
}
}
class LazyImage {
constructor(url) {
this.url = url;
}
draw() {
if(!this.image)
this.image = new Image(this.url);
}
this.image.draw();
}
function drawImage(img) {
console.log(`准备绘制图片...`);
img.draw();
console.log(`准备绘制图片...`);
}
ES6 proxy 是一个官方的代理模式的实现