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:
A)
operation
that can be called after it, and so on.ReserveTicketOperation
has public BuyTicketOperation execute();
BuyTicketOperation
has public RenderTicketOperation execute();
B)
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
Which design pattern represents a way to access all the objects in a collection? Explanation: Iterator pattern represents a way to access the elements of a collection object in sequential manner without the need to know its underlying representation.
Singleton Design pattern is a type of creational design pattern.
GoF Definition Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With