Java 相当于 python 装饰器

时间:2021-04-24 19:09:06

标签: java spring spring-boot decorator

在python中,您可以制作如下装饰器功能。注意:我从 https://www.ritchieng.com/python/decorators-kwargs-args/

复制并粘贴了此示例
def printAllDecorator(func):
    def inner(*args, **kwargs):
        print ('Arguments for args: {}'.format(args))
        print ('Arguments for kwargs: {}'.format(kwargs))
        return func(*args, **kwargs)
    return inner

@printAllDecorator
def multiply(a, b):
    return a * b

>>> multiply(9,4)
Arguments for args: (9, 4)
Arguments for kwargs: {}
36

Java 中有这样的东西吗?现在,假设我有以下内容。

Java 接口:

public interface MyInterface{
    String helloWorld();
}

实现该接口的类,我希望能够对其进行装饰:

// package & imports...

public MyClassToDecorate implements MyInterface {
    @Override
    String helloWorld(){
        return "hello world!";
    }
}

现在,如果我想为它制作一个装饰器,我会制作另一个这样的类:

public MyDecorator implements MyInterface {
    private MyInterface myInterface;

    public MyDecorator(MyClassToDecorate myClassToDecorate){
        myInterface = myClassToDecorate;
    }
    
    @Override
    String helloWorld(){
        return "From the decorator: " + myClassToDecorate.helloWorld();
    }
}

这一切都很好。但是...我的情况是我有 10 个不同的接口,每个接口都有 20 个或更多的功能,我想将这些功能中的每一个都包装在一个装饰器中。而装饰器对于它们中的每一个来说都是完全相同的代码。

如果您想知道我这样做是为了什么:我有一个 java spring 应用程序,我想模拟数据库故障。有 10 个不同的存储库接口。我想为每个存储库接口制作一个装饰器类,每个存储库接口都要求我覆盖至少 20 个函数。 10 个存储库 * 每个至少 20 个函数 = 至少 200 个函数,我必须一遍又一遍地编写相同的装饰器。

在python中,我的解决方案是只编写一次装饰器函数,如下所示:

# note: This isn't the exact logic I'm going to be using in my actual code.
#       But this is a simple example to illustrate the kind of decorator I'm going for.
def someDecoratorFunction(func):
    def wrapper(*args, **kwargs):
        x = random.random()
        if x < .80:
            # forward request to actual repository 
            func(*args, **kwargs)
        else: 
            # simulate database access failure
            raise RuntimeError('Failed to open database')
    return wrapper

然后我会创建 20 个新的装饰器类,每个类看起来像这样:

class ProxyEmployeeRepository(EmployeeRepositoryInterface):

    def __init__(self, realFileRepository):
        self.realFileRepository = realFileRepository


    @someDecoratorFunction
    def functionOne():
        return self.realFileRepository.functionOne()

    @someDecoratorFunction
    def functionTwo();
        return self.realFileRepository.functionTwo()

    # do the same thing for all of the other functions... 

这并不太乏味..是的,我需要制作 10 个类,每个类至少有 20 个函数,但至少我可以用一个简单的 @decoratorFunctionName 将装饰器包裹在每个函数周围。

有没有任何方法可以在java中做到这一点?还是 Java Spring?

0 个答案:

没有答案
相关问题