JackMahoney
JackMahoney

Reputation: 3433

Design pattern for interface that determines order of method invocation

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?

I considered:

Any thoughts or suggestions are greatly appreciated. Thanks

Upvotes: 5

Views: 2589

Answers (4)

user1717259
user1717259

Reputation: 2863

Have a look at the Fluent Builder pattern.

One example of this is here.

http://blog.crisp.se/2013/10/09/perlundholm/another-builder-pattern-for-java

The idea is that you have an 'tree of allowable methods'. Each level of the tree is defined in one interface. So you have an 'order of interfaces'. All the methods in each interface do their job (which has to be void) and then returns another interface, corresponding to the next level of the tree.

Upvotes: 3

Shane Voisard
Shane Voisard

Reputation: 1145

Perhaps Template Method Pattern, where your public interface defines the program skeleton of an algorithm in a public method, called template method, which defers some steps to private methods.

Or perhaps Command Pattern, where

an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

Upvotes: 2

Rob
Rob

Reputation: 11733

Uh, the answer to this one is simple: there is a pattern for this already amongst the 23 in the Gang of Four: Template Method.

The whole idea is that you are codifying exactly what you are talking about a sequence of operations, but you are allowing each individual operation to be, in Meyer's terms 'open to extension.'

If you are not sure what those operations are until runtime, then TM will not work.

Upvotes: 2

GhostCat
GhostCat

Reputation: 140427

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".

Upvotes: 4

Related Questions