Java Reference
In-Depth Information
LISTING 6‐3: SoftDrinksMachine implementation of the DrinksMachine abstract class
public class SoftDrinksMachine extends DrinksMachine {
public Drink dispenseDrink() {
return new SoftDrink();
}
}
LISTING 6‐4: The Drink interface
public interface Drink {}
LISTING 6‐5: SoftDrink implementation of the Drink interface
public class SoftDrink implements Drink {
SoftDrink() {
System.out.println("Soft drink");
}
}
LISTING 6‐6: Coffee implementation of the Drink interface
public class Coffee implements Drink {
Coffee() {
System.out.println("Coffee");
}
}
This implementation shows how the subclasses of the DrinksMachine abstract class determine the
drink that is dispensed. This allows any implementation of the DrinksMachine class to dispense
any object of the Drink type. Each subclass of the DrinksMachine 's abstract class determines which
drinks are dispensed.
This is a simple implementation in which the dispenseDrink method dispenses only one type of drink.
A more illustrative example would show the dispenseDrink method receiving the name of a drink and
then constructing and returning the requested drink object. Listing 6‐7 shows how to achieve this.
LISTING 6‐7: CoffeeType enum
public enum CoffeeType {EXPRESSO, LATTE}
public Drink dispenseDrink(CoffeeType type) {
Drink coffee = null;
switch (type) {
continues
Search WWH ::




Custom Search