将方法调用添加到类中的每个方法

Nao*_*aor 7 c# java design-patterns

我上课有很多方法:

public class A {
    public string method1() {
        return "method1";
    }
    public string method2() {
        return "method2";
    }
    public string method3() {
        return "method3";
    }
    .
    .
    .
    public string methodN() {
        return "methodN";
    }
}
Run Code Online (Sandbox Code Playgroud)

我想在每个方法中添加对doSomething()的调用,例如:

public string methodi() {
    doSomething();
    return "methodi";
}
Run Code Online (Sandbox Code Playgroud)

这样做的最佳方法是什么?有没有合适的设计模式?

And*_*s_D 7

这是AOP(面向方面​​编程)的典型用例.您将为方法调用定义插入点,AOP引擎会将正确的代码添加到类文件中.当您想要添加日志语句而不会混乱源文件时,通常会使用此方法.

对于java,您可以添加aspectj

对于C#和.NET,请查看此博客.看起来像一个好的首发.


Mic*_*ßer 5

使用AOP已经是一个很好的答案,这也是我的第一个想法.

我试图找出一个没有AOP的好方法,并提出了这个想法(使用Decorator模式):

interface I {
  String method1();
  String method2();
  ...
  String methodN();
}

class IDoSomethingDecorator implements I {
  private final I contents;
  private final Runnable commonAction;

  IDoSomethingDecorator(I decoratee, Runnable commonAction){
    this.contents = decoratee;
    this.commonAction = commonAction;
  }

  String methodi() {
    this.commonAction().run();
    return contents.methodi();
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以装饰A的构造(它实现了我):

I a = new IDoSomethingDecorator(new A(),doSomething);
Run Code Online (Sandbox Code Playgroud)

它基本上没有火箭科学,事实上会产生比你的第一个想法更多的代码,但你能够注入共同的行动,并将额外的行动与A类本身分开.此外,您可以轻松将其关闭或仅在测试中使用它.