5

Lambda重构面向对象的设计模式

 2 years ago
source link: https://perkins4j2.github.io/posts/2762600/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Lambda重构面向对象的设计模式

发表于

2020-10-09

| 分类于 架构

| 阅读次数: 55

本文字数: 2.7k

|

阅读时长 ≈ 2 分钟

Lambda表达式避免了采用策略设计模式时僵化的模板代码。

Validator numericValidator = 
new Validator((String s) -> s.matches("[a-z]+"));
boolean b1 = numericValidator.validate("aaaa");
Validator lowerCaseValidator =
new Validator((String s) -> s.matches("\\d+"));
boolean b2 = lowerCaseValidator.validate("bbbb");

通过传递Lambda表达式,直接插入不同的行为,不再需要继承。

public void processCustomer(int id, Consumer<Customer> makeCustomerHappy){ 
Customer c = Database.getCustomerWithId(id);
makeCustomerHappy.accept(c);
}
new OnlineBankingLambda().processCustomer(1337, (Customer c) ->
System.out.println("Hello " + c.getName());

观察者模式

无需显式地实例化观察者对象,直接传递Lambda表达式表示需要执行的行为即可。

f.registerObserver((String tweet) -> { 
if(tweet != null && tweet.contains("money")){
System.out.println("Breaking news in NY! " + tweet);
}
});
f.registerObserver((String tweet) -> {
if(tweet != null && tweet.contains("queen")){
System.out.println("Yet another news in London... " + tweet);
}
});

责任链模式

将处理对象作为函数的一个实例,或者更确切地说作为UnaryOperator-

的一个实例。为了链接这些函数,你需要使用andThen方法对其进行构造。

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?!!")


Supplier<Product> loanSupplier = Loan::new; 
Loan loan = loanSupplier.get();

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);
}

假设你希望保存具有三个参数(两个参数为Integer类型,一个参数为String
类型)的构造函数;为了完成这个任务,你需要创建一个特殊的函数接口TriFunction。

public interface TriFunction<T, U, V, R>{ 
R apply(T t, U u, V v);
}
Map<String, TriFunction<Integer, Integer, String, Product>> map
= new HashMap<>();


Runnable r2 = () -> System.out.println("Hello");

doSomething(() -> System.out.println("Danger danger!!"));

doSomething((Task)() -> System.out.println("Danger danger!!"));

有条件的延迟执行

logger.log(Level.FINER, () -> "Problem: " + generateDiagnostic());

public void log(Level level, Supplier<String> msgSupplier){
if(logger.isLoggable(level)){
log(level, msgSupplier.get());
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK