TypeScript设计模式(4):装饰器模式

什么是装饰器模式?

装饰器模式 (Decorator Pattern) 是一种设计模式,允许在不修改原有类代码的前提下,通过装饰方式来扩展它的功能。在 TypeScript 中,我们可以利用装饰器函数来实现这一点。

装饰器模式的优点

  • 增量原有类的功能而不修改它的代码
  • 可以通过层层闭包来组合功能
  • 提高代码的重用性和可维护性

TypeScript 中装饰器的基本用法

TypeScript 支持使用 装饰器 (装饰器函数) 来扩展类、方法、属性和参数。装饰器实际上是一个函数,它可以将一个类或方法作为参数,并返回修改后的值。

简单例子

typescript 复制代码
function Logger(target: Function) {
  console.log(`类 ${target.name} 被创建`);
}

@Logger
class Person {
  constructor() {
    console.log("Person 实例创建");
  }
}

const p = new Person();

在此例子中, @Logger 装饰器会在 Person 类创建时被调用,它相当于对 Person 类进行了一次处理。

装饰器传递参数

typescript 复制代码
function WithTemplate(template: string, hookId: string) {
  return function (constructor: any) {
    const hookElement = document.getElementById(hookId);
    if (hookElement) {
      hookElement.innerHTML = template;
    }
  };
}

@WithTemplate("<h1>你好,TypeScript!</h1>", "app")
class App {}

这里的 WithTemplate 装饰器会将指定的 HTML 模板添加到 DOM 元素中。

方法装饰器

typescript 复制代码
function LogMethod(target: any, methodName: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;
  descriptor.value = function (...args: any[]) {
    console.log(`调用 ${methodName} 方法,参数:`, args);
    return originalMethod.apply(this, args);
  };
}

class Car {
  @LogMethod
  drive(speed: number) {
    console.log(`驾驶速度:${speed}`);
  }
}

const car = new Car();
car.drive(100);

这里的 @LogMethod 装饰器在每次调用 drive 方法时输出方法名和参数信息。

结论

装饰器模式是一种强大而很有用的模式,在 TypeScript 中,我们可以使用它来扩展类、方法和属性的功能而不需要修改源代码。这样能很好地提高代码的重用性和维护性。

相关推荐
wanghowie31 分钟前
01.08 Java基础篇|设计模式深度解析
java·开发语言·设计模式
syt_10132 小时前
设计模式之-中介者模式
设计模式·中介者模式
明洞日记2 小时前
【设计模式手册023】外观模式 - 如何简化复杂系统
java·设计模式·外观模式
游戏23人生3 小时前
c++ 语言教程——16面向对象设计模式(五)
开发语言·c++·设计模式
watersink4 小时前
Agent 设计模式
开发语言·javascript·设计模式
老朱佩琪!4 小时前
Unity策略模式
unity·设计模式·策略模式
o0向阳而生0o4 小时前
116、23种设计模式之责任链模式(23/23)(完结撒花)
设计模式·责任链模式
山沐与山21 小时前
【设计模式】Python模板方法模式:从入门到实战
python·设计模式·模板方法模式
阿拉斯攀登1 天前
设计模式:责任链模式
设计模式·责任链模式
崎岖Qiu1 天前
【设计模式笔记18】:并发安全与双重检查锁定的单例模式
java·笔记·单例模式·设计模式