确定方法调用顺序的接口设计模式 [英] Design pattern for interface that determines order of method invocation

查看:358
本文介绍了确定方法调用顺序的接口设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用多种方法创建Java接口。但是我希望接口的用户只能按我定义的顺序或顺序调用方法。例如,不应在 reserveTicket()之前调用 buyTicket()问:是否有设计模式或有关此操作的提示?

I want to create a Java interface with a number methods. But I want the user of the interface to only be able to invoke methods in the sequence or order that I define. For instance buyTicket() should not be called before reserveTicket(). Q: Is there a design pattern or any tips on how to go about this?

我认为:


  • A)

  • A)


  • 接口被换行,仅显示下一个可能方法。每次调用方法都会返回一个新的操作,可以在该操作之后调用,依此类推。

  • 所以 ReserveTicketOperation 具有个公共BuyTicketOperation execute();

  • 然后 BuyTicketOperation 具有个公共RenderTicketOperation execute();

  • Interface is wrapped, only showing the next possible method. Each invocation of a method returns a new operation that can be called after it, and so on.
  • So ReserveTicketOperation has public BuyTicketOperation execute();
  • Then BuyTicketOperation has public RenderTicketOperation execute();

B)


  • 使用某种上下文状态机来记录

  • Use some kind of context state machine that records the position of execution using enums and has a factory for obtaining the next operation.

任何想法或建议,不胜感激。谢谢

Any thoughts or suggestions are greatly appreciated. Thanks

推荐答案

我的直觉:这是完全不做的模式。

My immediate feeling: this is the don't do it at all pattern.

如果方法的内在逻辑要求它们始终以一定顺序调用它们;那么您将暴露一个实现细节,这将使使用界面做错事情变得非常容易。

If the inner logic of your methods requires them to always call them in a certain order; then you are exposing an implementation detail that will make it very easy to use your interface to do something wrong.

含义:而不是试图以某种方式强制您的客户端代码为了遵守某些特定的顺序,您应该以不需要客户端代码关心顺序的方式设计界面。

Meaning: instead of trying to somehow force your "client code" to adhere to some specific order you should design your interfaces in a way that the client code doesn't need to care about "order".

在您的特定示例中,问题似乎是票证对象可以保留或购买;当然,只有购买的票可以退回,退款... ...

In your particular example the problem seems to be that a ticket object can be "reserved" or "bought"; and of course, only "bought" tickets can be turned back, refunded, ...

在这种情况下,解决方案可能实际上是 预订票和购买票的不同类。然后,您不必担心有人会尝试退还仅保留的机票。

In this case, the "solution" could be to have actually different classes for "reserved" tickets and "bought" tickets. Then you don't need to worry that somebody tries to refund a ticket that is only "reserved".

这篇关于确定方法调用顺序的接口设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆