您在這裡

Ordering Food From The Chef

26 七月, 2019 - 09:51
Available under Creative Commons-ShareAlike 4.0 International License. Download for free at http://cnx.org/contents/402b20ad-c01f-45f1-9743-05eadb1f710e@37.6

To order food from an IChef, a Vegetarian object simply calls cookVeggie, passing itself as one of the pa¬rameters, while a Carnivore object would call cookMeat, passing itself as one of the parameters as well. The Vegetarian and Carnivore objects only deal with the IChef object at the highest level of abstraction and do not care what the concrete IChef is. The polymorphism machinery guarantees that the correct method in the concrete IChef will be called and the appropriate kind of food will be returned to the AEater caller. The table below shows the code for Vegetarian and Carnivore, and sample client code using these classes.

Table 3.10 Concrete implementations
public class Vegetarian extends AEater {
        // other methods elided
        public String order(IChef c, int n) {
                return c.cookVeggie(this, n);
         }
}
public class Carnivore extends AEater {
         // other methods elided
         public String order(IChef c, int n) {
                 return c.cookMeat(this, n);
         }
}
Table 3.11 Client code
public void party(AEater e, IChef c, int n) {
        System.out.println(e.order(c, n));
}
        // blah blah blah...
        AEater John = new Carnivore();
        AEater Mary = new Vegetarian();
        party(Mary, ChefWong.Singleton, 2);
        party(John,ChefZung.Singleton, 1);

The above design is an example of what is called the visitor pattern.

  • The abstract class AEater and its concrete subclasses are called the hosts. The method public String order(IChef c, Object n) is called the hook method. Each concrete subclasses of AEater knows exactly to call the appropriate method on the IChef parameter, but does know and need not how the IChef concretely perforns its task. This allows an open-ended number of ways to cook the appropriate kinds of food.
  • The chef interface IChef and all of its concrete implementations are called visitors. When an IChef performs cookMeat/cookVeggie, it knows that its host is a Carnivore/Vegetarian and can only call the methods of Carnivore/Vegetarian to cook a dish. Java static type checking will fag an error should there be a call on the host to getCarot in the method cookMeat. This is makes the interaction between hosts (Vegetarian and Carnivore) and visitors (IChef and all of its concrete implementations) much more robust.