其他分享
首页 > 其他分享> > 装饰器Decorator

装饰器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
2、abstract抽象类实现装饰器:
https://www.xin3721.com/ArticlecSharp/c11756.html

标签:return,int,list,func,time,total,装饰,Decorator
来源: https://www.cnblogs.com/fanyang1/p/16629965.html