<< Chapter < Page | Chapter >> Page > |
interface IChef {
String cookVeggie(Vegetarian h, Integer n);String cookMeat(Carnivore h, Integer n);
} |
public class ChefWong implements IChef {public static final ChefWong Singleton
= new ChefWong();private ChefWong() {}
public String cookVeggie(Vegetarian h, Integer n) {return n + " portion(s) of " +
h.getCarrot() + ", " +h.getSalt();
}public String cookMeat(
Carnivore h, Integer n) {return n + " portion(s) of " +
h.getMeat() + ", " +h.getPepper();
}} |
public class ChefZung implements IChef {public static final ChefZung Singleton
= new ChefZung();private ChefZung() {}
public String cookVeggie(Vegetarian h, Integer n) {
return n + " portion(s) of " +h.getCorn() + ", " +
h.getSalt();}
public String cookMeat(Carnivore h, Integer n) {
return n + " portion(s) of " +h.getChicken() + ", " +
h.getPepper() +", " + h.getSalt();
}} |
To order food from an IChef , a Vegetarian object simply calls cookVeggie, passing itself as one of the parameters, 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.
public class Vegetarian extends AEater {
// other methods elidedpublic String order(IChef c, int n) {
return c.cookVeggie(this, n);}
} |
public class Carnivore extends AEater {
// other methods elidedpublic String order(IChef c, int n) {
return c.cookMeat(this, n);}
} |
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.
Notification Switch
Would you like to follow the 'Principles of object-oriented programming' conversation and receive update notifications?