OnJava8-Examples/enums/CarWash.java

89 lines
1.8 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// enums/CarWash.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-06-15 17:47:35 -07:00
import java.util.*;
public class CarWash {
public enum Cycle {
UNDERBODY {
@Override
2015-12-02 09:20:27 -08:00
void action() {
System.out.println("Spraying the underbody");
}
2015-06-15 17:47:35 -07:00
},
WHEELWASH {
@Override
2015-12-02 09:20:27 -08:00
void action() {
System.out.println("Washing the wheels");
}
2015-06-15 17:47:35 -07:00
},
PREWASH {
@Override
2015-12-02 09:20:27 -08:00
void action() {
System.out.println("Loosening the dirt");
}
2015-06-15 17:47:35 -07:00
},
BASIC {
@Override
2015-12-02 09:20:27 -08:00
void action() {
System.out.println("The basic wash");
}
2015-06-15 17:47:35 -07:00
},
HOTWAX {
@Override
2015-12-02 09:20:27 -08:00
void action() {
System.out.println("Applying hot wax");
}
2015-06-15 17:47:35 -07:00
},
RINSE {
@Override
2015-12-02 09:20:27 -08:00
void action() {
System.out.println("Rinsing");
}
2015-06-15 17:47:35 -07:00
},
BLOWDRY {
@Override
2015-12-02 09:20:27 -08:00
void action() {
System.out.println("Blowing dry");
}
2015-06-15 17:47:35 -07:00
};
abstract void action();
}
EnumSet<Cycle> cycles =
EnumSet.of(Cycle.BASIC, Cycle.RINSE);
2017-01-20 21:30:44 -08:00
public void add(Cycle cycle) {
cycles.add(cycle);
}
2015-06-15 17:47:35 -07:00
public void washCar() {
for(Cycle c : cycles)
c.action();
}
@Override
2017-01-20 21:30:44 -08:00
public String toString() {
return cycles.toString();
}
2015-06-15 17:47:35 -07:00
public static void main(String[] args) {
CarWash wash = new CarWash();
2015-11-03 12:00:44 -08:00
System.out.println(wash);
2015-06-15 17:47:35 -07:00
wash.washCar();
// Order of addition is unimportant:
wash.add(Cycle.BLOWDRY);
wash.add(Cycle.BLOWDRY); // Duplicates ignored
wash.add(Cycle.RINSE);
wash.add(Cycle.HOTWAX);
2015-11-03 12:00:44 -08:00
System.out.println(wash);
2015-06-15 17:47:35 -07:00
wash.washCar();
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
[BASIC, RINSE]
The basic wash
Rinsing
[BASIC, HOTWAX, RINSE, BLOWDRY]
The basic wash
Applying hot wax
Rinsing
Blowing dry
2015-09-07 11:44:36 -06:00
*/