让相同的接口表现出不同的行为

值代理

  1. class Percentage {
  2. constructor(percent) {
  3. this.percent = percent;
  4. }
  5. toString() {
  6. return `${this.percent}%`;
  7. }
  8. valueOf() {
  9. return this.perect / 100;
  10. }
  11. }
  12. let fivePercent = new Percentage(5);
  13. console.log(fivePercent.toString()); // 5%
  14. console.log(`1005%是${100 * fivePercent}`); // 100的5%是5

属性代理

  1. class Property {
  2. constructor(value, name='') {
  3. this._value = value;
  4. this.name = name;
  5. }
  6. get value() {
  7. return this._value;
  8. }
  9. set value(newValue) {
  10. if(this._value === newValue) return;
  11. console.log(`给${this.name}赋了一个新的值: ${newValue}`);
  12. this._value = newValue;
  13. }
  14. }
  15. class Creature {
  16. constructor() {
  17. this._agility = new Property(50, 'agility');
  18. }
  19. get agility() {
  20. return this._agility.value;
  21. }
  22. set agility(value) {
  23. this._agility.value = value;
  24. }
  25. }
  26. let c = new Creature();
  27. c.agility = 60;
  28. c.agility = 70;

保护代理

  1. class Car {
  2. drive() {
  3. console.log(`开车中...`);
  4. }
  5. }
  6. class CarProxy {
  7. constructor(driver){
  8. this.driver = driver;
  9. this._car = new Car();
  10. }
  11. drive() {
  12. if (this.driver.age >= 18) {
  13. this._car.driver();
  14. } else {
  15. console.log(`现在还太年经,还没有到驾驶的年龄...`);
  16. }
  17. }
  18. }
  19. class Driver {
  20. constructor(age) {
  21. this.age = age;
  22. }
  23. }
  24. let car1 = new Car();
  25. car1.drive(); // 开车中..
  26. let car2 = new CarProxy(new Driver(15));
  27. car2.drive(); // 现在还太年经,还没有到驾驶的年龄...

虚拟代理

  1. class Image {
  2. constructor(url) {
  3. this.url = url;
  4. console.log(`从${this.url}加载了图片...`);
  5. }
  6. draw() {
  7. console.log(`从${this.url}绘制了图片...`);
  8. }
  9. }
  10. class LazyImage {
  11. constructor(url) {
  12. this.url = url;
  13. }
  14. draw() {
  15. if(!this.image)
  16. this.image = new Image(this.url);
  17. }
  18. this.image.draw();
  19. }
  20. function drawImage(img) {
  21. console.log(`准备绘制图片...`);
  22. img.draw();
  23. console.log(`准备绘制图片...`);
  24. }

ES6 proxy 是一个官方的代理模式的实现