OOP设计模式 - 隐式调用超级方法或其他解决方案

时间:2015-05-17 08:08:16

标签: java oop

是否存在一种设计模式(可能但不一定是OOP),您可以隐式(非显式地)调用一个函数/方法A每次调用其他方法时形成对象中的所有其他方法?

例如:

//pseudocode

    class Foo {

       int count = 0;

       void synchronized countUp(){
         count++;
       }

       void doSomethingFirst(){
       //call countUp() implicitly here
       }

       void doSomethingSecond(){
       //call countUp() implicitly here
       }
    }

例如,有没有办法在Java中使用注释?我可以标记需要调用超级方法或其他东西的方法。所以这就像是对super的隐含调用。我不是说这是个好主意我只是想知道它是否可以用某种设计模式来完成。

2 个答案:

答案 0 :(得分:1)

您可以扩展该类并覆盖countUp()方法。使所有方法都受到保护,并从子类中调用所需的超类方法。

class Boo extends Foo {
    @Override
    void countUp() {
        setUp(); 
        super.countUp();
        tearDown();
    }
}

为了使其更通用,您可以使用观察者模式:

  • 使Foo类可观察
  • 通过反射

    获取init的所有方法

    Foo.class.getMethods()

  • 将所有方法包装在一个类中并注册为观察者

答案 1 :(得分:1)

你可能会复制Spring MVC框架使用的系统(我不认为它是一种设计模式)。它依赖于将继承的方法设为final,并为后代提供可重载的方法。

使用部分示例代码(在Java中):

   final void doSomethingFirst(){
      countUp();
      doSomethingFirstInternal();
   }

   protected void doSomethingFirstInternal() {
      // Empty implementation that descendants can override when necessary.
   }

我并不是说这是一个好主意 - 您需要100%确定您的代码应该首先执行。但这是一个选项,粗心的程序员不能引入错误,因为他们忘了调用super()。