3分鐘看完Java 8——史上最強Java 8新特性總結之第三篇 函數語言程式設計技巧
目錄
·
·策略模式(Strategy Pattern)
·模板方法模式(Template Method Pattern)
·觀察者模式(Observer Pattern)
·責任鏈模式(Chain of Responsibility Pattern)
·簡單工廠模式(Simple Factory Pattern)
·
改寫設計模式
策略模式(Strategy Pattern)
1. 改寫前
a) ValidationStrategy.java
1 public interface ValidationStrategy { 2 3boolean execute(String s); 4 5 }
b) IsNumeric.java
1 public class IsNumeric implements ValidationStrategy { 2 3public boolean execute(String s) { 4return s.matches("\\d+"); 5} 6 7 }
c) IsAllLowerCase.java
1 public class IsAllLowerCase implements ValidationStrategy { 2 3public boolean execute(String s) { 4return s.matches("[a-z]+"); 5} 6 7 }
d) Validator.java
1 public class Validator { 2private final ValidationStrategy strategy; 3 4public Validator(ValidationStrategy v) { 5this.strategy = v; 6} 7 8public boolean validate(String s) { 9return strategy.execute(s); 10} 11 }
e) Test.java
1 public class Test { 2 3public static void main(String[] args) { 4Validator numericValidator = new Validator(new IsNumeric()); 5boolean b1 = numericValidator.validate("aaaa"); 6System.out.println(b1); // false 7Validator lowerCaseValidator = new Validator(new IsAllLowerCase()); 8boolean b2 = lowerCaseValidator.validate("bbbb"); 9System.out.println(b2); // true 10} 11 12 }
2.改寫後
a) Test.java
1 public class Test { 2 3public static void main(String[] args) { 4Validator numericValidator = new Validator((String s) -> s.matches("\\d+")); 5boolean b1 = numericValidator.validate("aaaa"); 6System.out.println(b1); // false 7Validator lowerCaseValidator = new Validator(s -> s.matches("[a-z]+")); 8boolean b2 = lowerCaseValidator.validate("bbbb"); 9System.out.println(b2); // true 10} 11 12 }
模板方法模式(Template Method Pattern)
1. 改寫前
a) Customer.java
1 public class Customer { 2 3private int id; 4private String name; 5 6public Customer(int id, String name) { 7this.id = id; 8this.name = name; 9} 10 11public int getId() { 12return id; 13} 14 15public void setId(int id) { 16this.id = id; 17} 18 19public String getName() { 20return name; 21} 22 23public void setName(String name) { 24this.name = name; 25} 26 27 }
b) OnlineBanking.java
1 public abstract class OnlineBanking { 2 3public void processCustomer(int id) { 4Customer c = new Customer(id, "Jhon"); 5makeCustomerHappy(c); 6} 7 8abstract void makeCustomerHappy(Customer c); 9 10 }
2.改寫後
a) OnlineBankingLambda.java
1 import java.util.function.Consumer; 2 3 public class OnlineBankingLambda { 4 5public void processCustomer(int id, Consumer<Customer> makeCustomerHappy) { 6Customer c = new Customer(id, "Jhon"); 7makeCustomerHappy.accept(c); 8} 9 10 }
b) Test.java
1 public class Test { 2 3public static void main(String[] args) { 4new OnlineBankingLambda().processCustomer(1337, (Customer c) -> System.out.println("Hello " + c.getName())); 5} 6 7 }
觀察者模式(Observer Pattern)
1. 改寫前
a) Observer.java
1 public interface Observer { 2 3void notify(String tweet); 4 5 }
b) NYTimes.java
1 public class NYTimes implements Observer { 2 3public void notify(String tweet) { 4if (tweet != null && tweet.contains("money")) { 5System.out.println("Breaking news in NY! " + tweet); 6} 7} 8 9 }
c) Guardian.java
1 public class Guardian implements Observer { 2 3public void notify(String tweet) { 4if (tweet != null && tweet.contains("queen")) { 5System.out.println("Yet another news in London... " + tweet); 6} 7} 8 9 }
d) LeMonde.java
1 public class LeMonde implements Observer { 2 3public void notify(String tweet) { 4if (tweet != null && tweet.contains("wine")) { 5System.out.println("Today cheese, wine and news! " + tweet); 6} 7} 8 9 }
e) Subject.java
1 public interface Subject { 2 3void registerObserver(Observer o); 4 5void notifyObservers(String tweet); 6 7 }
f) Feed.java
1 public class Feed implements Subject { 2 3private final List<Observer> observers = new ArrayList<>(); 4 5public void registerObserver(Observer o) { 6this.observers.add(o); 7} 8 9public void notifyObservers(String tweet) { 10observers.forEach(o -> o.notify(tweet)); 11} 12 13 }
g) Test.java
1 public class Test { 2 3public static void main(String[] args) { 4Feed f = new Feed(); 5f.registerObserver(new NYTimes()); 6f.registerObserver(new Guardian()); 7f.registerObserver(new LeMonde()); 8f.notifyObservers("The queen said her favourite book is Java 8 in Action!"); 9} 10 11 }
2.改寫後
a) Test.java
1 public class Test { 2 3public static void main(String[] args) { 4Feed f = new Feed(); 5f.registerObserver((String tweet) -> { 6if (tweet != null && tweet.contains("money")) { 7System.out.println("Breaking news in NY! " + tweet); 8} 9}); 10f.registerObserver((tweet) -> { 11if (tweet != null && tweet.contains("queen")) { 12System.out.println("Yet another news in London... " + tweet); 13} 14}); 15f.registerObserver((tweet) -> { 16if (tweet != null && tweet.contains("wine")) { 17System.out.println("Today cheese, wine and news! " + tweet); 18} 19}); 20f.notifyObservers("The queen said her favourite book is Java 8 in Action!"); 21} 22 23 }
責任鏈模式(Chain of Responsibility Pattern)
1. 改寫前
a) ProcessingObject.java
1 public abstract class ProcessingObject<T> { 2 3protected ProcessingObject<T> successor; 4 5public void setSuccessor(ProcessingObject<T> successor) { 6this.successor = successor; 7} 8 9public T handle(T input) { 10T r = handleWork(input); 11if (successor != null) { 12return successor.handle(r); 13} 14return r; 15} 16 17protected abstract T handleWork(T input); 18 }
b) HeaderTextProcessing.java
1 public class HeaderTextProcessing extends ProcessingObject<String> { 2 3public String handleWork(String text) { 4return "From Raoul, Mario and Alan: " + text; 5} 6 7 }
c) SpellCheckerProcessing.java
1 public class SpellCheckerProcessing extends ProcessingObject<String> { 2 3public String handleWork(String text) { 4return text.replaceAll("labda", "lambda"); 5} 6 7 }
d) Test.java
1 public class Test { 2 3public static void main(String[] args) { 4ProcessingObject<String> p1 = new HeaderTextProcessing(); 5ProcessingObject<String> p2 = new SpellCheckerProcessing(); 6p1.setSuccessor(p2); 7String result = p1.handle("Aren't labdas really sexy?!!"); 8System.out.println(result); 9} 10 11 }
2.改寫後
a) Test.java
1 public class Test { 2 3public static void main(String[] args) { 4UnaryOperator<String> headerProcessing = (String text) -> "From Raoul, Mario and Alan: " + text; 5UnaryOperator<String> spellCheckerProcessing = (String text) -> text.replaceAll("labda", "lambda"); 6Function<String, String> pipeline = headerProcessing.andThen(spellCheckerProcessing); 7String result = pipeline.apply("Aren't labdas really sexy?!!"); 8System.out.println(result); 9} 10 11 }
簡單工廠模式(Simple Factory Pattern)
1. 改寫前
a) Product.java
1 public interface Product { 2 }
b) Loan.java
1 public class Loan implements Product { 2 }
c) Stock.java
1 public class Stock implements Product { 2 }
d) Bond.java
1 public class Bond implements Product { 2 }
e) ProductFactory.java
1 public class ProductFactory { 2 3public static Product createProduct(String name) { 4switch (name) { 5case "loan": 6return new Loan(); 7case "stock": 8return new Stock(); 9case "bond": 10return new Bond(); 11default: 12throw new RuntimeException("No such product " + name); 13} 14} 15 16 }
f) Test.java
1 public class Test { 2 3public static void main(String[] args) { 4Product p = ProductFactory.createProduct("loan"); 5} 6 7 }
2. 改寫後
a) ProductFactory.java
1 import java.util.HashMap; 2 import java.util.Map; 3 import java.util.function.Supplier; 4 5 public class ProductFactory { 6 7final static Map<String, Supplier<Product>> map = new HashMap<>(); 8 9static { 10map.put("loan", Loan::new); 11map.put("stock", Stock::new); 12map.put("bond", Bond::new); 13} 14 15public static Product createProduct(String name) { 16Supplier<Product> p = map.get(name); 17if (p != null) return p.get(); 18throw new IllegalArgumentException("No such product " + name); 19} 20 21 }
b) Test.java
1 public class Test { 2 3public static void main(String[] args) { 4Product p = ProductFactory.createProduct("loan"); 5} 6 7 }
高階函式與柯里化
1. 高階函式(Higher-order Function):滿足以下任意一個條件都是高階函式。
a) 接受至少一個函式作為引數。
b) 返回的結果是一個函式。
2. 柯里化(Currying):假設有一個函式f(x, y) ,柯里化就是把多個引數的函式f轉化為一個引數的函式g,並且函式g的返回值一個新函式,即 f(x, y) = (g(x))(y) 。
3. 柯里化好處:靈活、複用。
4. 舉例
a) 柯里化前
1 public class Test { 2 3public static double converter(double x, double f, double b) { 4return x * f + b; 5} 6 7public static void main(String[] args) { 8double gbp = converter(1000, 0.6, 0); 9System.out.println(gbp); 10} 11 12 }
b) 柯里化後
1 public class Test { 2 3public static DoubleUnaryOperator curriedConverter(double f, double b) { 4return (double x) -> x * f + b; 5} 6 7public static void main(String[] args) { 8DoubleUnaryOperator convertCtoF = curriedConverter(9.0 / 5, 32); 9DoubleUnaryOperator convertUSDtoGBP = curriedConverter(0.6, 0); 10DoubleUnaryOperator convertKmtoMi = curriedConverter(0.6214, 0); 11 12double gbp = convertUSDtoGBP.applyAsDouble(1000); 13System.out.println(gbp); 14} 15 16 }
作者:netoxi
出處:http://www.cnblogs.com/netoxi
本文版權歸作者和部落格園共有,歡迎轉載,未經同意須保留此段宣告,且在文章頁面明顯位置給出原文連線。歡迎指正與交流。