目录
· 改写设计模式
· 模板方法模式(Template Method Pattern)
· 责任链模式(Chain of Responsibility Pattern)
· 简单工厂模式(Simple Factory Pattern)
· 高阶函数与柯里化
改写设计模式
策略模式(Strategy Pattern)
1. 改写前
a) ValidationStrategy.java
public interface ValidationStrategy { boolean execute(String s); }
b) IsNumeric.java
public class IsNumeric implements ValidationStrategy { public boolean execute(String s) {
return s.matches("\\d+");
} }
c) IsAllLowerCase.java
public class IsAllLowerCase implements ValidationStrategy { public boolean execute(String s) {
return s.matches("[a-z]+");
} }
d) Validator.java
public class Validator {
private final ValidationStrategy strategy; public Validator(ValidationStrategy v) {
this.strategy = v;
} public boolean validate(String s) {
return strategy.execute(s);
}
}
e) Test.java
public class Test { public static void main(String[] args) {
Validator numericValidator = new Validator(new IsNumeric());
boolean b1 = numericValidator.validate("aaaa");
System.out.println(b1); // false
Validator lowerCaseValidator = new Validator(new IsAllLowerCase());
boolean b2 = lowerCaseValidator.validate("bbbb");
System.out.println(b2); // true
} }
2.改写后
a) Test.java
public class Test { public static void main(String[] args) {
Validator numericValidator = new Validator((String s) -> s.matches("\\d+"));
boolean b1 = numericValidator.validate("aaaa");
System.out.println(b1); // false
Validator lowerCaseValidator = new Validator(s -> s.matches("[a-z]+"));
boolean b2 = lowerCaseValidator.validate("bbbb");
System.out.println(b2); // true
} }
模板方法模式(Template Method Pattern)
1. 改写前
a) Customer.java
public class Customer { private int id;
private String name; public Customer(int id, String name) {
this.id = id;
this.name = name;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} }
b) OnlineBanking.java
public abstract class OnlineBanking { public void processCustomer(int id) {
Customer c = new Customer(id, "Jhon");
makeCustomerHappy(c);
} abstract void makeCustomerHappy(Customer c); }
2.改写后
a) OnlineBankingLambda.java
import java.util.function.Consumer; public class OnlineBankingLambda { public void processCustomer(int id, Consumer<Customer> makeCustomerHappy) {
Customer c = new Customer(id, "Jhon");
makeCustomerHappy.accept(c);
} }
b) Test.java
public class Test { public static void main(String[] args) {
new OnlineBankingLambda().processCustomer(1337, (Customer c) -> System.out.println("Hello " + c.getName()));
} }
观察者模式(Observer Pattern)
1. 改写前
a) Observer.java
public interface Observer { void notify(String tweet); }
b) NYTimes.java
public class NYTimes implements Observer { public void notify(String tweet) {
if (tweet != null && tweet.contains("money")) {
System.out.println("Breaking news in NY! " + tweet);
}
} }
c) Guardian.java
public class Guardian implements Observer { public void notify(String tweet) {
if (tweet != null && tweet.contains("queen")) {
System.out.println("Yet another news in London... " + tweet);
}
} }
d) LeMonde.java
public class LeMonde implements Observer { public void notify(String tweet) {
if (tweet != null && tweet.contains("wine")) {
System.out.println("Today cheese, wine and news! " + tweet);
}
} }
e) Subject.java
public interface Subject { void registerObserver(Observer o); void notifyObservers(String tweet); }
f) Feed.java
public class Feed implements Subject { private final List<Observer> observers = new ArrayList<>(); public void registerObserver(Observer o) {
this.observers.add(o);
} public void notifyObservers(String tweet) {
observers.forEach(o -> o.notify(tweet));
} }
g) Test.java
public class Test { public static void main(String[] args) {
Feed f = new Feed();
f.registerObserver(new NYTimes());
f.registerObserver(new Guardian());
f.registerObserver(new LeMonde());
f.notifyObservers("The queen said her favourite book is Java 8 in Action!");
} }
2.改写后
a) Test.java
public class Test { public static void main(String[] args) {
Feed f = new Feed();
f.registerObserver((String tweet) -> {
if (tweet != null && tweet.contains("money")) {
System.out.println("Breaking news in NY! " + tweet);
}
});
f.registerObserver((tweet) -> {
if (tweet != null && tweet.contains("queen")) {
System.out.println("Yet another news in London... " + tweet);
}
});
f.registerObserver((tweet) -> {
if (tweet != null && tweet.contains("wine")) {
System.out.println("Today cheese, wine and news! " + tweet);
}
});
f.notifyObservers("The queen said her favourite book is Java 8 in Action!");
} }
责任链模式(Chain of Responsibility Pattern)
1. 改写前
a) ProcessingObject.java
public abstract class ProcessingObject<T> { protected ProcessingObject<T> successor; public void setSuccessor(ProcessingObject<T> successor) {
this.successor = successor;
} public T handle(T input) {
T r = handleWork(input);
if (successor != null) {
return successor.handle(r);
}
return r;
} protected abstract T handleWork(T input);
}
b) HeaderTextProcessing.java
public class HeaderTextProcessing extends ProcessingObject<String> { public String handleWork(String text) {
return "From Raoul, Mario and Alan: " + text;
} }
c) SpellCheckerProcessing.java
public class SpellCheckerProcessing extends ProcessingObject<String> { public String handleWork(String text) {
return text.replaceAll("labda", "lambda");
} }
d) Test.java
public class Test { public static void main(String[] args) {
ProcessingObject<String> p1 = new HeaderTextProcessing();
ProcessingObject<String> p2 = new SpellCheckerProcessing();
p1.setSuccessor(p2);
String result = p1.handle("Aren't labdas really sexy?!!");
System.out.println(result);
} }
2.改写后
a) Test.java
public class Test { public static void main(String[] args) {
UnaryOperator<String> headerProcessing = (String text) -> "From Raoul, Mario and Alan: " + text;
UnaryOperator<String> spellCheckerProcessing = (String text) -> text.replaceAll("labda", "lambda");
Function<String, String> pipeline = headerProcessing.andThen(spellCheckerProcessing);
String result = pipeline.apply("Aren't labdas really sexy?!!");
System.out.println(result);
} }
简单工厂模式(Simple Factory Pattern)
1. 改写前
a) Product.java
public interface Product {
}
b) Loan.java
public class Loan implements Product {
}
c) Stock.java
public class Stock implements Product {
}
d) Bond.java
public class Bond implements Product {
}
e) ProductFactory.java
public class ProductFactory { public static Product createProduct(String name) {
switch (name) {
case "loan":
return new Loan();
case "stock":
return new Stock();
case "bond":
return new Bond();
default:
throw new RuntimeException("No such product " + name);
}
} }
f) Test.java
public class Test { public static void main(String[] args) {
Product p = ProductFactory.createProduct("loan");
} }
2. 改写后
a) ProductFactory.java
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier; public class ProductFactory { final static Map<String, Supplier<Product>> map = new HashMap<>(); static {
map.put("loan", Loan::new);
map.put("stock", Stock::new);
map.put("bond", Bond::new);
} public static Product createProduct(String name) {
Supplier<Product> p = map.get(name);
if (p != null) return p.get();
throw new IllegalArgumentException("No such product " + name);
} }
b) Test.java
public class Test { public static void main(String[] args) {
Product p = ProductFactory.createProduct("loan");
} }
高阶函数与柯里化
1. 高阶函数(Higher-order Function):满足以下任意一个条件都是高阶函数。
a) 接受至少一个函数作为参数。
b) 返回的结果是一个函数。
2. 柯里化(Currying):假设有一个函数 f(x, y) ,柯里化就是把多个参数的函数f转化为一个参数的函数g,并且函数g的返回值一个新函数,即 f(x, y) = (g(x))(y) 。
3. 柯里化好处:灵活、复用。
4. 举例
a) 柯里化前
public class Test { public static double converter(double x, double f, double b) {
return x * f + b;
} public static void main(String[] args) {
double gbp = converter(1000, 0.6, 0);
System.out.println(gbp);
} }
b) 柯里化后
public class Test { public static DoubleUnaryOperator curriedConverter(double f, double b) {
return (double x) -> x * f + b;
} public static void main(String[] args) {
DoubleUnaryOperator convertCtoF = curriedConverter(9.0 / 5, 32);
DoubleUnaryOperator convertUSDtoGBP = curriedConverter(0.6, 0);
DoubleUnaryOperator convertKmtoMi = curriedConverter(0.6214, 0); double gbp = convertUSDtoGBP.applyAsDouble(1000);
System.out.println(gbp);
} }
作者:netoxi
出处:http://www.cnblogs.com/netoxi
本文版权归作者和博客园共有,欢迎转载,未经同意须保留此段声明,且在文章页面明显位置给出原文连接。欢迎指正与交流。