Skip to content

Commit 0529ac2

Browse files
committed
[add] add refactor and debug techniques in Java 8 module.
1 parent c322201 commit 0529ac2

File tree

8 files changed

+401
-0
lines changed

8 files changed

+401
-0
lines changed

java8/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,13 @@
4545
- ParallelStreams: 并行流计算 1~n 的和,分别使用指令式,串行迭代流,并行迭代流,基本类型流,有副作用的流
4646
- ForkJoinSumCalculator: 使用分支/合并框架执行并行求和
4747
- WordCount: Spliterator: splitable iterator
48+
49+
## 高效 Java 8 编程
50+
51+
- StrategyMain: 策略模式
52+
- TemplateMain: 模版方法
53+
- ObserverMain: 观察者模式
54+
- ChainOfResponsibilityMain: 责任链模式
55+
- FactoryMain: 工厂模式
56+
- Debugging: 查看栈跟踪
57+
- Peek: 使用日志调试
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.brianway.learning.java8.effective.tech;
2+
3+
import java.util.function.Function;
4+
import java.util.function.UnaryOperator;
5+
6+
/**
7+
* 责任链模式
8+
*/
9+
public class ChainOfResponsibilityMain {
10+
11+
public static void main(String[] args) {
12+
//old school
13+
ProcessingObject<String> p1 = new HeaderTextProcessing();
14+
ProcessingObject<String> p2 = new SpellCheckerProcessing();
15+
p1.setSuccessor(p2);
16+
String result1 = p1.handle("Aren't labdas really sexy?!!");
17+
System.out.println(result1);
18+
19+
// with lambdas
20+
UnaryOperator<String> headerProcessing =
21+
(String text) -> "From Raoul, Mario and Alan: " + text;
22+
UnaryOperator<String> spellCheckerProcessing =
23+
(String text) -> text.replaceAll("labda", "lambda");
24+
Function<String, String> pipeline = headerProcessing.andThen(spellCheckerProcessing);
25+
String result2 = pipeline.apply("Aren't labdas really sexy?!!");
26+
System.out.println(result2);
27+
}
28+
29+
static private abstract class ProcessingObject<T> {
30+
protected ProcessingObject<T> successor;
31+
32+
public void setSuccessor(ProcessingObject<T> successor) {
33+
this.successor = successor;
34+
}
35+
36+
public T handle(T input) {
37+
T r = handleWork(input);
38+
if (successor != null) {
39+
return successor.handle(r);
40+
}
41+
return r;
42+
}
43+
44+
abstract protected T handleWork(T input);
45+
}
46+
47+
static private class HeaderTextProcessing
48+
extends ProcessingObject<String> {
49+
public String handleWork(String text) {
50+
return "From Raoul, Mario and Alan: " + text;
51+
}
52+
}
53+
54+
static private class SpellCheckerProcessing
55+
extends ProcessingObject<String> {
56+
public String handleWork(String text) {
57+
return text.replaceAll("labda", "lambda");
58+
}
59+
}
60+
}
61+
62+
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.brianway.learning.java8.effective.tech;
2+
3+
import java.util.Arrays;
4+
import java.util.List;
5+
6+
/**
7+
* 查看栈跟踪
8+
*/
9+
public class Debugging {
10+
public static void main(String[] args) {
11+
// Arrays.asList(1, 2, 3).stream()
12+
// .map(Debugging::divideByZero)
13+
// .forEach(System.out::println);
14+
15+
List<Point> points = Arrays.asList(new Point(12, 2), null);
16+
//points.stream().map(p -> p.getX()).forEach(System.out::println);
17+
points.stream().map(Point::getX).forEach(System.out::println);
18+
}
19+
20+
private static class Point {
21+
private int x;
22+
private int y;
23+
24+
private Point(int x, int y) {
25+
this.x = x;
26+
this.y = y;
27+
}
28+
29+
public int getX() {
30+
return x;
31+
}
32+
33+
public void setX(int x) {
34+
this.x = x;
35+
}
36+
}
37+
38+
public static int divideByZero(int n) {
39+
return n / 0;
40+
}
41+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.brianway.learning.java8.effective.tech;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
import java.util.function.Supplier;
6+
7+
/**
8+
* 工厂模式
9+
*/
10+
public class FactoryMain {
11+
12+
public static void main(String[] args) {
13+
Product p1 = ProductFactory.createProduct("loan");
14+
p1.printClassName();
15+
16+
// with lambdas
17+
Supplier<Product> loanSupplier = Loan::new;
18+
Product p2 = loanSupplier.get();
19+
p2.printClassName();
20+
21+
Product p3 = ProductFactory.createProductLambda("loan");
22+
p3.printClassName();
23+
}
24+
25+
static private class ProductFactory {
26+
public static Product createProduct(String name) {
27+
switch (name) {
28+
case "loan":
29+
return new Loan();
30+
case "stock":
31+
return new Stock();
32+
case "bond":
33+
return new Bond();
34+
default:
35+
throw new RuntimeException("No such product " + name);
36+
}
37+
}
38+
39+
public static Product createProductLambda(String name) {
40+
Supplier<Product> p = map.get(name);
41+
if (p != null) return p.get();
42+
throw new RuntimeException("No such product " + name);
43+
}
44+
}
45+
46+
private interface Product {
47+
default void printClassName() {
48+
System.out.println(getClass().getSimpleName());
49+
}
50+
}
51+
52+
static private class Loan implements Product {
53+
}
54+
55+
static private class Stock implements Product {
56+
}
57+
58+
static private class Bond implements Product {
59+
}
60+
61+
final static private Map<String, Supplier<Product>> map = new HashMap<>();
62+
63+
static {
64+
map.put("loan", Loan::new);
65+
map.put("stock", Stock::new);
66+
map.put("bond", Bond::new);
67+
}
68+
}
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
package com.brianway.learning.java8.effective.tech;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* 观察者模式
8+
*/
9+
public class ObserverMain {
10+
11+
public static void main(String[] args) {
12+
//old school
13+
Subject f = new Feed();
14+
f.registerObserver(new NYTimes());
15+
f.registerObserver(new Guardian());
16+
f.registerObserver(new LeMonde());
17+
f.notifyObservers("The queen said her favourite book is Java 8 in Action!");
18+
19+
// with lambdas
20+
Feed feedLambda = new Feed();
21+
22+
feedLambda.registerObserver((String tweet) -> {
23+
if (tweet != null && tweet.contains("money")) {
24+
System.out.println("Breaking news in NY! " + tweet);
25+
}
26+
});
27+
feedLambda.registerObserver((String tweet) -> {
28+
if (tweet != null && tweet.contains("queen")) {
29+
System.out.println("Yet another news in London... " + tweet);
30+
}
31+
});
32+
33+
feedLambda.notifyObservers("Money money money, give me money!");
34+
35+
}
36+
37+
interface Observer {
38+
void inform(String tweet);
39+
}
40+
41+
interface Subject {
42+
void registerObserver(Observer o);
43+
44+
void notifyObservers(String tweet);
45+
}
46+
47+
static private class NYTimes implements Observer {
48+
@Override
49+
public void inform(String tweet) {
50+
if (tweet != null && tweet.contains("money")) {
51+
System.out.println("Breaking news in NY!" + tweet);
52+
}
53+
}
54+
}
55+
56+
static private class Guardian implements Observer {
57+
@Override
58+
public void inform(String tweet) {
59+
if (tweet != null && tweet.contains("queen")) {
60+
System.out.println("Yet another news in London... " + tweet);
61+
}
62+
}
63+
}
64+
65+
static private class LeMonde implements Observer {
66+
@Override
67+
public void inform(String tweet) {
68+
if (tweet != null && tweet.contains("wine")) {
69+
System.out.println("Today cheese, wine and news! " + tweet);
70+
}
71+
}
72+
}
73+
74+
static private class Feed implements Subject {
75+
private final List<Observer> observers = new ArrayList<>();
76+
77+
public void registerObserver(Observer o) {
78+
this.observers.add(o);
79+
}
80+
81+
public void notifyObservers(String tweet) {
82+
observers.forEach(o -> o.inform(tweet));
83+
}
84+
}
85+
86+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.brianway.learning.java8.effective.tech;
2+
3+
import static java.util.stream.Collectors.toList;
4+
5+
import java.util.List;
6+
import java.util.stream.Stream;
7+
8+
/**
9+
* 使用日志调试
10+
*/
11+
public class Peek {
12+
13+
public static void main(String[] args) {
14+
15+
List<Integer> result = Stream.of(2, 3, 4, 5)
16+
.peek(x -> System.out.println("taking from stream: " + x))
17+
.map(x -> x + 17)
18+
.peek(x -> System.out.println("after map: " + x))
19+
.filter(x -> x % 2 == 0)
20+
.peek(x -> System.out.println("after filter: " + x))
21+
.limit(3)
22+
.peek(x -> System.out.println("after limit: " + x))
23+
.collect(toList());
24+
}
25+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.brianway.learning.java8.effective.tech;
2+
3+
/**
4+
* 策略模式
5+
*/
6+
public class StrategyMain {
7+
8+
public static void main(String[] args) {
9+
// old school
10+
Validator v1 = new Validator(new IsNumeric());
11+
System.out.println(v1.validate("aaaa"));
12+
Validator v2 = new Validator(new IsAllLowerCase());
13+
System.out.println(v2.validate("bbbb"));
14+
15+
// with lambdas
16+
Validator v3 = new Validator((String s) -> s.matches("\\d+"));
17+
System.out.println(v3.validate("aaaa"));
18+
Validator v4 = new Validator((String s) -> s.matches("[a-z]+"));
19+
System.out.println(v4.validate("bbbb"));
20+
}
21+
22+
interface ValidationStrategy {
23+
boolean execute(String s);
24+
}
25+
26+
static private class IsAllLowerCase implements ValidationStrategy {
27+
public boolean execute(String s) {
28+
return s.matches("[a-z]+");
29+
}
30+
}
31+
32+
static private class IsNumeric implements ValidationStrategy {
33+
public boolean execute(String s) {
34+
return s.matches("\\d+");
35+
}
36+
}
37+
38+
static private class Validator {
39+
private final ValidationStrategy strategy;
40+
41+
public Validator(ValidationStrategy v) {
42+
this.strategy = v;
43+
}
44+
45+
public boolean validate(String s) {
46+
return strategy.execute(s);
47+
}
48+
}
49+
}

0 commit comments

Comments
 (0)