一、策略模式
jdk8之前写法
public interface ValidationStrategy {
boolean validate(String s);
}
public class IsNumeric implements ValidationStrategy {
public boolean validate(String s){
if(null == s) return false;
return s.matches("\\d+");
}
}
public class Validator{
private final ValidationStrategy strategy;
public Validator(ValidationStrategy vs){
this.strategy = vs;
}
public boolean validate(String s){
return strategy.validate(s);
}
}
lambda优化
Validator validator = new Validator((String s) -> {
if(null == s) return false;
return s.matches("[a-z]+");
});
二、模板方法
jdk8之前写法
abstract class Template {
public void execute(Map param){
MsgTemplate t = loadTemplate();
t.replace(param)
}
abstract MsgTemplate loadTemplate();
}
lambda优化
public class ClassPathTemplate extends Template{
@Overide
public MsgTemplate loadTemplate() {
return MsgTemplateBuilder.build(new File(""));
}
}
三、观察者模式
jdk8之前写法
interface Observer {
void notify(String msg);
}
class NewsObserver implements Observer{
public void notify(String msg) {
System.out.println("news:" + news);
}
}
interface Subject{
void registerObserver(Observer o);
void notifyObservers(String msg);
}
class News implements Subject{
private final List<Observer> observers = new ArrayList<>();
public void registerObserver(Observer o) {
this.observers.add(o);
}
public void notifyObservers(String msg) {
observers.forEach(o -> o.notify(msg));
}
}
News n = new News();
n.registerObserver(new NewsObserver());
n.notifyObservers("Today News...");
lambda优化
n.registerObserver((String msg) -> {
System.out.println("Today News" + msg);
});
四、责任链模式
jdk8之前写法
public abstract class ProcessingChain<T> {
protected ProcessingChain<T> next;
public void nextChain(ProcessingChain<T> next){
this.next = next;
}
public T process(T t){
t = doWork(t);
if(null != next){
return next.process(t);
}
return r;
}
abstract T doWork(T t);
}
public class HeadProcessingChain extends ProcessingChain<String> {
public String doWork(String s){
return text + "Hello";
}
}
public class TailProcessingChain extends ProcessingChain<String> {
public String doWork(String s){
return text + " World";
}
}
ProcessingObject<String> p1 = new HeadProcessingChain();
ProcessingObject<String> p2 = new TailProcessingChain();
p1.nextChain(p2);
String result = p1.process("Console : ");
System.out.println(result);
lambda优化
UnaryOperator<String> headProcessing = (String text) -> text + "Hello";
UnaryOperator<String> tailProcessing = (String text) -> text + " World";
Function<String, String> pipeline = headProcessing.andThen(tailProcessing);
String result = pipeline.apply("Console :");
System.out.println(result);