版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangbingfengf98/article/details/86532391
Although Java is not a functional language, Java 8 Lamda Expressions and Method References allow we to program in a functional style.
We can think OO abstracts data, FP abstracts behavior.
In computer science, functional programming is a programming paradigm. It set once and never changed.
for example:
// functional/Strategize.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
interface Strategy {
String approach(String msg);
}
class Soft implements Strategy {
public String approach(String msg) {
return msg.toLowerCase() + "?";
}
}
class Unrelated {
static String twice(String msg) {
return msg + " " + msg;
}
}
public class Strategize {
Strategy strategy;
String msg;
Strategize(String msg) {
strategy = new Soft(); // [1]
this.msg = msg;
}
void communicate() {
System.out.println(strategy.approach(msg));
}
void changeStrategy(Strategy strategy) {
this.strategy = strategy;
}
public static void main(String[] args) {
Strategy[] strategies = {
new Strategy() { // [2]
public String approach(String msg) {
return msg.toUpperCase() + "!";
}
},
msg -> msg.substring(0, 5), // [3] // lambda expression
Unrelated::twice // [4] // Java 8 method reference
};
Strategize s = new Strategize("Hello there");
s.communicate();
for (Strategy newStrategy : strategies) {
s.changeStrategy(newStrategy); // [5]
s.communicate(); // [6]
}
}
}
/* Output:
hello there?
HELLO THERE!
Hello
Hello there Hello there
*/
references:
1. On Java 8 - Bruce Eckel
2. https://en.wikipedia.org/wiki/Functional_programming#Concepts
3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/functional/Strategize.java