【问题标题】:How to Force 3rd party implementing/inheriting class to run a generic method in java?如何强制第 3 方实现/继承类在 java 中运行泛型方法?
【发布时间】:2013-07-24 17:00:53
【问题描述】:

编辑 1:我所说的泛型并不是指 Java 泛型类的泛型方法,而是我编写的在使用我的程序时必不可少的方法。

我正在尝试编写一个程序(类似于流程集成器),它允许第 3 方开发人员将他们自己的功能部件添加到任务网。这些片段是由类创建的对象,它们有一个runProcess()-方法(类实现了specialRunnable)。

我不想在调用 object 的 runProcess()- 方法时强制写入日志条目。但是,我不希望实现(写入日志)既不在第 3 方类中,也不在进行方法调用的类中。

我已经搜索并尝试通过继承和实现接口来做到这一点,但还没有找到解决方案。这是我希望它如何工作的示例:

 public abstract class Process{

 public void runProcess(){   
 // when runProcess() is called all specialized processes write to log first
 writeToLog();
 // then do their thing which is defined in their class
 doYourProcessSpecificThing();

 }

 public void writeToLog(){ 
 //writing to log comes here
 }

 // specialized processes have to define what is done
 public abstract void doYourProcessSpecificThing(); 

专业类:

public class Special3rdPartyProcess  extends Process implements specialRunnable{

runProcess(){
super.runProcess();
}

doYourProcessSpecificThing(){
// this is where the magic happens
}

总结一下我想要的:我希望所有进程都使用 runProcess() 命令启动,并且我想要一个日志条目,只要它完成,但我不想要第 3 方开发人员决定如何或是否写入条目。我也不希望这样:

writeToLog();
task1.runProcess();

writeToLog();
task2.runProcess

谢谢!

【问题讨论】:

  • 使用面向方面的编程。
  • 我认为将基类作为 3rd 方开发人员的 API 通常是一个糟糕的主意。日志记录似乎是IProcess(或您设计的任何接口)的外部关注点。为什么不做类似的事情:IProcessManager.Process(work) 其中work 只关心一件事:运行特殊进程。 IProcessManager 会让您决定是否登录,而不是将您的第 3 方开发人员与您自己的实施细节联系起来。
  • @assylias runProcess() 方法的作用取决于类,例如。我有 SpecProcess1 和 SpecProcess2 类,它们以不同的方式实现该方法。但是,我希望日志记录保持一致。因此,我不能使 runProcess() 方法成为最终方法,因为所有子类都将使用相同的实现。
  • @user2615429 具体部分在doYourProcessSpecificThing,不在runProcess。

标签: java inheritance logging implementation forcing


【解决方案1】:

如果您将runProcess 方法设为final,那么子类将无法覆盖您的方法,这可以确保调用writeToLog。

您可以使writeToLog private 不公开实现。

你可以将doYourProcessSpecificThingprotected设为不能直接调用,但子类仍然可以定义自己的实现。

这称为Template Method Pattern。这允许实施者(您)定义可以覆盖哪些特定行为,同时保留对整个流程/算法的控制。

【讨论】:

  • 谢谢!这很有帮助。 - 操作
【解决方案2】:

您可以简单地将 runProcess 在基类中设置为 final,因此子类不能覆盖它:

public abstract class Process{

 public final void runProcess(){   
   writeToLog();
   doYourProcessSpecificThing();
 }

 //private: implementation detail
 private void writeToLog(){ 
 }

 //protected: calling classes don't need to know about this method
 protected abstract void doYourProcessSpecificThing(); 

还有你的子类:

public class Special3rdPartyProcess  extends Process implements specialRunnable{
  protected final void doYourProcessSpecificThing(){
    // this is where the magic happens
  }
}

然后客户端代码简单地做:

Special3rdPartyProcess spp = ...;
spp.runProcess();

【讨论】:

    猜你喜欢
    • 2016-07-06
    • 2014-10-28
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    相关资源
    最近更新 更多