OnJava8-Examples/functional/Strategize.java

59 lines
1.3 KiB
Java
Raw Normal View History

2015-11-14 16:18:05 -08:00
// functional/Strategize.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-11-14 16:18:05 -08:00
interface Strategy {
2015-12-02 09:20:27 -08:00
String approach(String msg);
2015-11-14 16:18:05 -08:00
}
2015-12-02 09:20:27 -08:00
class Soft implements Strategy {
public String approach(String msg) {
return msg.toLowerCase() + "?";
2015-11-14 16:18:05 -08:00
}
}
2015-12-02 09:20:27 -08:00
class Unrelated {
static String twice(String msg) {
return msg + " " + msg;
2015-11-14 16:18:05 -08:00
}
}
public class Strategize {
2015-12-02 09:20:27 -08:00
Strategy strategy;
String msg;
Strategize(String msg) {
strategy = new Soft(); // [1]
2015-12-02 09:20:27 -08:00
this.msg = msg;
}
void communicate() {
System.out.println(strategy.approach(msg));
}
void changeStrategy(Strategy strategy) {
this.strategy = strategy;
2015-11-14 16:18:05 -08:00
}
public static void main(String[] args) {
2015-12-02 09:20:27 -08:00
Strategy[] strategies = {
new Strategy() { // [2]
2015-12-02 09:20:27 -08:00
public String approach(String msg) {
return msg.toUpperCase() + "!";
2015-11-14 16:18:05 -08:00
}
2015-12-02 09:20:27 -08:00
},
msg -> msg.substring(0, 5), // [3]
Unrelated::twice // [4]
2015-11-14 16:18:05 -08:00
};
2015-12-02 09:20:27 -08:00
Strategize s = new Strategize("Hello there");
s.communicate();
for(Strategy newStrategy : strategies) {
s.changeStrategy(newStrategy); // [5]
s.communicate(); // [6]
2015-12-02 09:20:27 -08:00
}
2015-11-14 16:18:05 -08:00
}
}
/* Output:
hello there?
2015-12-02 09:20:27 -08:00
HELLO THERE!
2015-11-14 16:18:05 -08:00
Hello
2015-12-02 09:20:27 -08:00
Hello there Hello there
2015-11-14 16:18:05 -08:00
*/