装饰器Decorator

Golang

func warp(f func([]int) int) func([]int) int {
	return func(list []int) int {
		start := time.Now()
		s := f(list)
		end := time.Now()
		fmt.Println(end.Sub(start))
		return s
	}
}

list := []int{1,2,6,6}
total := warp(sum)(list)

Nodejs

// js休眠函数
function sleep(ms) {
	return new Promise(resolve => setTimeout(resolve, ms));
}

async function sum(list) {
	let total = 0;
	for (const v of list) {
		total += v;
	}
	await sleep(1000);
	return total;
}

// 函数装饰器,js目前不支持类、属性装饰器,只能用typescript
function timerDecorator(func) {
	return async function() {
		console.time();
		const result = await func.apply(this, arguments);
		console.timeEnd();
		return result;
	}
}

timerDecorator(sum)([1,2,3]).then((res) => {
	console.log(res);
});

Python

def costime(func):
	def warp(*args, **kwargs):
		start = time.time()
		res = func(*args, **kwargs)
		end = time.time()
		print(end-start)
		return res
	return warp

@costime
def sum(*args):

C#

1、Attribute特性实现装饰器:
https://blog.csdn.net/weixin_43263355/article/details/110137016
2abstract抽象类实现装饰器:
https://www.xin3721.com/ArticlecSharp/c11756.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值