开发者

Represent a workflow in an interface in Java

I have similar methods that needs to be implemented for different concepts. But call of the methods should be in order. For example let's say my methods are:

m1, m2, m3, m4. There will more than one implementations of them. So, I wanted to collect them in a Java interface. But as they depend on each other, it seemed a bit strange to do so. Then I decided to define a single method in the interface which ex开发者_JAVA百科ecutes the other ones in order, but this time the interface does not reflect its purpose.

So, what is the best practice to represent such ordered method calls with Java interface and implementations of it?

Thanks in advance


If the flow is well defined, you can use a kind of strategy pattern by defining an abstract class which implements the flow, allowing sub-classes to define the flow methods only. Ex:

public interface MyInterface {
  m1();
  m2();
  m3();
  m4();
  flow();
}

public abstract class Strategy implements MyInterface {      
  public final void flow() {
     //implement the flow only
     m1();
     m2();
     m3();
     m4();
  }
}

Normally the strategy pattern would allow sub-classes to override the flow() method, but since you don't want to do that, you mark the flow method as final. This way, the clients will worry only about the m1,...,m4 implementations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜