Friday 15 July 2011

java - How to enforce sequence in function calls -


Suppose that I want to design a class whose client must call the function in a particular sequence, such as,
  hasNext (); the upcoming(); Or, as a very common example, with a class  CookFood  methods:  
  class CookFood {getListOfItems (); MixAllItems (); heat(); } In the second example, I want to apply that only after mixing the items should be mixed and this mixture should be done only after mixing. Are there any known patterns or good practices that apply the sequence of calls to the function?   

You may be interested in. This is not a good match for all the cases you have presented, but the idea is that each operation gives something to implement an interface that lets you do the next operation. Since you can get the object only by executing the object in the correct order, you will be forced to execute them in the right order.

  • Em> then you can think of

    Pattern can you get an example of the CanWearSocks interface, in which only The following is the method. CanWearShoes putOnSocks ()

    When you call putOnSocks () , you can use your CanWearShoes < / Code> get examples, which only have the following method.

      SockAndShoeWearear putOnShoes ()   

    When you call putOnShoes () you wear some socks and shoes , And you were forced to do it in the correct order.

    What's particularly good is that you can actually use the same object in both cases, but because the method signing only returns the interface type, the code uses only the interface methods (Unless the code is stuttering, and type the object separately).

    Example

    Here is a consistent example that implements the walking pattern, that is, it ensures that you use a next cracker before the nexagator.

      Public class stepbuilderation {Inter Next checker face {NextGetter hasNext ()}; } NextGetter {Object Next (); Next Investigator (And); } Fixed class ArrayExample {Final constant integer [] ints = new integer [] {1, 2, 3, 4}; Public Static NextChecker iterate () {Return iterative (0); } Private Static NextChecker iterate (Last int i) {New NextChecker () Back {Public NextGetter hasNext () (if (i & lt; ints.length) {New NextGetter ()) {Public Object Next () {return ints [i ]; } Public Next Investigator (and) (return iter 1); }}; } And {return tap; }}}; }} Public static zero main (string [] args) {NextChecker nc = ArrayExample.iterate (); While (nc! = Null) {NextGetter ng = nc.hasNext (); If (ng! = Null) {System.out.println (ng.next ()); Nc = ng.more (); }}}}   

    Output is:

      1 2 3 4    

  • No comments:

    Post a Comment