装饰者模式

装饰者模式

定义

装饰者模式能够在不改变对象自身的基础上,在程序运行期间给对象动态的增加职责
JS 中可以通过高阶函数来实现装饰者模式

1
2
3
4
5
6
7
8
9
10
11
12
function getUserInfo( userId ) {
console.log("我获取了用户的信息通过userId");
return `用户信息:${userId} ....`
}
function reportToServer(decorateTarget) {
return function(..args) {
console.log(“有人在获取用户信息啦");
if (typeof decorateTarget !== "function") return;
return decorateTarget.apply(this,...args);
}
}
const getUser = reportToServer(getUserInfo)

TS 中的装饰器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//类装饰器语法 Class Decorator
@decoratorName
class TestClass{}
//成员装饰器语法 Member Decorator
class TestClass{
@decoratorName
public testProp:string
}
//参数装饰器语法 Parmeter Decorator
class TestClass{
@decoratorName
public method(
@decoratorName
prop:string
){}
}

类装饰器 Class Decorator

类装饰器函数接收一个 target 参数,这个参数就是装饰的类本身
类装饰器有两种返回值:

  1. void : 当没有返回值的时候,整个类的行为不会被返回值影响
  2. new Class : 装饰器返回一个类的时候,原先类的返回实例会被新的类实例替换返回

成员装饰器 Member Decorator

成员装饰器函数接收三个参数:

  1. target: 如果装饰器装饰的是静态成员,则 target 是类的本身,如果装饰的是实例成员,则 target 的该类的 prototype
  2. key: 代表当前修饰的键值
  3. descriptor: 该 key 的属性描述符,可读可写配置等
    1
    2
    3
    4
    5
    6
    7
    8
    9
    function memberDecorator(
    target: object,
    key:string,
    descriptor: PropertyDescriptor
    ){}
    class Test{
    @memberDecorator
    pbulic propName:string
    }

参数装饰器 Parmeter Decorator

参数装饰器函数接收三个参数:

  1. target: 与成员装饰器一致
  2. methodName: 代表当前方法的名称
  3. index: 被修饰参数在函数参数列表中的索引
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function parameterDecorator(
    target: object,
    methodName: string,
    index: number
    ){}
    class Test {
    public method(
    @parameterDecorator
    param: string
    ){}
    }

装饰器总结

  1. 装饰器会参与到最终 JS 运行
  2. 装饰器的运行时机:到这个类的时候就会立刻被执行
  3. 开启 TS 的相关配置可以将 TypeScript 的类型约束作为元数据放入运行时态中,TypeScript 将有机会在运行时态中进行类型约束

image.png


装饰者模式
http://blog.climbed.online/2023/11/24/Web -- Knowledge is infinite/编程思想/设计模式/装饰者模式/
作者
Z.K.
发布于
2023年11月24日
许可协议