目录
改写设计模式
策略模式(Strategy Pattern)
1. 改写前
a) ValidationStrategy.java
1 public interfaceValidationStrategy {2
3 booleanexecute(String s);4
5 }
b) IsNumeric.java
1 public class IsNumeric implementsValidationStrategy {2
3 public booleanexecute(String s) {4 return s.matches("\\d+");5 }6
7 }
c) IsAllLowerCase.java
1 public class IsAllLowerCase implementsValidationStrategy {2
3 public booleanexecute(String s) {4 return s.matches("[a-z]+");5 }6
7 }
d) Validator.java
1 public classValidator {2 private finalValidationStrategy strategy;3
4 publicValidator(ValidationStrategy v) {5 this.strategy =v;6 }7
8 public booleanvalidate(String s) {9 returnstrategy.execute(s);10 }11 }
e) Test.java
1 public classTest {2
3 public static voidmain(String[] args) {4 Validator numericValidator = new Validator(newIsNumeric());5 boolean b1 = numericValidator.validate("aaaa");6 System.out.println(b1); //false
7 Validator lowerCaseValidator = new Validator(newIsAllLowerCase());8 boolean b2 = lowerCaseValidator.validate("bbbb");9 System.out.println(b2); //true
10 }11
12 }
2.改写后
a) Test.java
1 public classTest {2
3 public static voidmain(String[] args) {4 Validator numericValidator = new Validator((String s) -> s.matches("\\d+"));5 boolean b1 = numericValidator.validate("aaaa");6 System.out.println(b1); //false
7 Validator lowerCaseValidator = new Validator(s -> s.matches("[a-z]+"));8 boolean b2 = lowerCaseValidator.validate("bbbb");9 System.out.println(b2); //true
10 }11
12 }
模板方法模式(Template Method Pattern)
1. 改写前
a) Customer.java
1 public classCustomer {2
3 private intid;4 privateString name;5
6 public Customer(intid, String name) {7 this.id =id;8 this.name =name;9 }10
11 public intgetId() {12 returnid;13 }14
15 public void setId(intid) {16 this.id =id;17 }18
19 publicString getName() {20 returnname;21 }22
23 public voidsetName(String name) {24 this.name =name;25 }26
27 }
b) OnlineBanking.java
1 public abstract classOnlineBanking {2
3 public void processCustomer(intid) {4 Customer c = new Customer(id, "Jhon");5 makeCustomerHappy(c);6 }7
8 abstract voidmakeCustomerHappy(Customer c);9
10 }
2.改写后
a) OnlineBankingLambda.java
1 importjava.util.function.Consumer;2
3 public classOnlineBankingLambda {4
5 public void processCustomer(int id, ConsumermakeCustomerHappy) {6 Customer c = new Customer(id, "Jhon");7 makeCustomerHappy.accept(c);8 }9
10 }
b) Test.java
1 public classTest {2
3 public static voidmain(String[] args) {4 new OnlineBankingLambda().processCustomer(1337, (Customer c) -> System.out.println("Hello " +c.getName()));5 }6
7 }
观察者模式(Observer Pattern)
1. 改写前
a) Observer.java
1 public interfaceObserver {2
3 voidnotify(String tweet);4
5 }
b) NYTimes.java
1 public class NYTimes implementsObserver {2
3 public voidnotify(String tweet) {4 if (tweet != null && tweet.contains("money")) {5 System.out.println("Breaking news in NY! " +tweet);6 }7 }8
9 }
c) Guardian.java
1 public class Guardian implementsObserver {2
3 public voidnotify(String tweet) {4 if (tweet != null && tweet.contains("queen")) {5 System.out.println("Yet another news in London... " +tweet);6 }7 }8
9 }
d) LeMonde.java
1 public class LeMonde implementsObserver {2
3 public voidnotify(String tweet) {4 if (tweet != null && tweet.contains("wine")) {5 System.out.println("Today cheese, wine and news! " +tweet);6 }7 }8
9 }
e) Subject.java
1 public interfaceSubject {2
3 voidregisterObserver(Observer o);4
5 voidnotifyObservers(String tweet);6
7 }
f) Feed.java
1 public class Feed implementsSubject {2
3 private final List observers = new ArrayList<>();4
5 public voidregisterObserver(Observer o) {6 this.observers.add(o);7 }8
9 public voidnotifyObservers(String tweet) {10 observers.forEach(o ->o.notify(tweet));11 }12
13 }
g) Test.java
1 public classTest {2
3 public static voidmain(String[] args) {4 Feed f = newFeed();5 f.registerObserver(newNYTimes());6 f.registerObserver(newGuardian());7 f.registerObserver(newLeMonde());8 f.notifyObservers("The queen said her favourite book is Java 8 in Action!");9 }10
11 }
2.改写后
a) Test.java
1 public classTest {2
3 public static voidmain(String[] args) {4 Feed f = newFeed();5 f.registerObserver((String tweet) ->{6 if (tweet != null && tweet.contains("money")) {7 System.out.println("Breaking news in NY! " +tweet);8 }9 });10 f.registerObserver((tweet) ->{11 if (tweet != null && tweet.contains("queen")) {12 System.out.println("Yet another news in London... " +tweet);13 }14 });15 f.registerObserver((tweet) ->{16 if (tweet != null && tweet.contains("wine")) {17 System.out.println("Today cheese, wine and news! " +tweet);18 }19 });20 f.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{2
3 protected ProcessingObjectsuccessor;4
5 public void setSuccessor(ProcessingObjectsuccessor) {6 this.successor =successor;7 }8
9 publicT handle(T input) {10 T r =handleWork(input);11 if (successor != null) {12 returnsuccessor.handle(r);13 }14 returnr;15 }16
17 protected abstractT handleWork(T input);18 }
b) HeaderTextProcessing.java
1 public class HeaderTextProcessing extends ProcessingObject{2
3 publicString handleWork(String text) {4 return "From Raoul, Mario and Alan: " +text;5 }6
7 }
c) SpellCheckerProcessing.java
1 public class SpellCheckerProcessing extends ProcessingObject{2
3 publicString handleWork(String text) {4 return text.replaceAll("labda", "lambda");5 }6
7 }
d) Test.java
1 public classTest {2
3 public static voidmain(String[] args) {4 ProcessingObject p1 = newHeaderTextProcessing();5 ProcessingObject p2 = newSpellCheckerProcessing();6 p1.setSuccessor(p2);7 String result = p1.handle("Aren't labdas really sexy?!!");8 System.out.println(result);9 }10
11 }
2.改写后
a) Test.java
1 public classTest {2
3 public static voidmain(String[] args) {4 UnaryOperator headerProcessing = (String text) -> "From Raoul, Mario and Alan: " +text;5 UnaryOperator spellCheckerProcessing = (String text) -> text.replaceAll("labda", "lambda");6 Function pipeline =headerProcessing.andThen(spellCheckerProcessing);7 String result = pipeline.apply("Aren't labdas really sexy?!!");8 System.out.println(result);9 }10
11 }
简单工厂模式(Simple Factory Pattern)
1. 改写前
a) Product.java
1 public interfaceProduct {2 }
b) Loan.java
1 public class Loan implementsProduct {2 }
c) Stock.java
1 public class Stock implementsProduct {2 }
d) Bond.java
1 public class Bond implementsProduct {2 }
e) ProductFactory.java
1 public classProductFactory {2
3 public staticProduct createProduct(String name) {4 switch(name) {5 case "loan":6 return newLoan();7 case "stock":8 return newStock();9 case "bond":10 return newBond();11 default:12 throw new RuntimeException("No such product " +name);13 }14 }15
16 }
f) Test.java
1 public classTest {2
3 public static voidmain(String[] args) {4 Product p = ProductFactory.createProduct("loan");5 }6
7 }
2. 改写后
a) ProductFactory.java
1 importjava.util.HashMap;2 importjava.util.Map;3 importjava.util.function.Supplier;4
5 public classProductFactory {6
7 final static Map> map = new HashMap<>();8
9 static{10 map.put("loan", Loan::new);11 map.put("stock", Stock::new);12 map.put("bond", Bond::new);13 }14
15 public staticProduct createProduct(String name) {16 Supplier p =map.get(name);17 if (p != null) returnp.get();18 throw new IllegalArgumentException("No such product " +name);19 }20
21 }
b) Test.java
1 public classTest {2
3 public static voidmain(String[] args) {4 Product 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 classTest {2
3 public static double converter(double x, double f, doubleb) {4 return x * f +b;5 }6
7 public static voidmain(String[] args) {8 double gbp = converter(1000, 0.6, 0);9 System.out.println(gbp);10 }11
12 }
b) 柯里化后
1 public classTest {2
3 public static DoubleUnaryOperator curriedConverter(double f, doubleb) {4 return (double x) -> x * f +b;5 }6
7 public static voidmain(String[] args) {8 DoubleUnaryOperator convertCtoF = curriedConverter(9.0 / 5, 32);9 DoubleUnaryOperator convertUSDtoGBP = curriedConverter(0.6, 0);10 DoubleUnaryOperator convertKmtoMi = curriedConverter(0.6214, 0);11
12 double gbp = convertUSDtoGBP.applyAsDouble(1000);13 System.out.println(gbp);14 }15
16 }
作者:netoxi
出处:http://www.cnblogs.com/netoxi
本文版权归作者和博客园共有,欢迎转载,未经同意须保留此段声明,且在文章页面明显位置给出原文连接。欢迎指正与交流。