装饰器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
posted @   codeIsArt  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示