匿名类和Lamda中的this区别###
匿名类中,this是本身。匿名类可以屏蔽包含类的变量。
Runnable runnable=new Runnable() {
@Override
public void run() {
int num=5;
System.out.println(num);
}
};
Lambda中this是包含类。不能屏蔽包含类的变量。
int num=10;
Runnable runnable=() -> {
int num=5;//报错 Lambda expression's local variable num cannot redeclare another local variable defined in an enclosing scope.
System.out.println(num);
};
**Lambda的类型取决于上下文,匿名类是初始化时决定的。**
Lambda不认识的情况:
public interface Task {
void execute();
static void doSomething(Runnable r){
r.run();
}
static void doSomething(Task t){
t.execute();
}
}
doSomething( () ->System.out.println("identity who?"));//这样不知道是谁了,要具体指定。
doSomething((Runnable) () ->System.out.println("identity who?"));
doSomething((Task) () ->System.out.println("identity who?"));
下面就是Lambda的重构的几种设计模式
策略模式###
public interface ValidationStrategy {
boolean execute(String str);
}
public class IsAllLowerCase implements ValidationStrategy{
@Override
public boolean execute(String str) {
return str.matches("[a-z]+");
}
}
public class IsNumeric implements ValidationStrategy{
@Override
public boolean execute(String str) {
return str.matches("\\d+");
}
}
public class Validator {
private final ValidationStrategy validationStrategy;
public Validator(ValidationStrategy validationStrategy) {
this.validationStrategy = validationStrategy;
}
public boolean validate(String str){
return validationStrategy.execute(str);
}
public static void main(String[] args) {
Validator validator1=new Validator((String str) -> str.matches("[a-z]+"));
boolean b1=validator1.validate("1avd");
Validator validator2=new Validator((String str) -> str.matches("\\d+"));
boolean b2=validator2.validate("gff");
}
}
模板方法###
import java.util.function.Consumer;
public class OnBankLambda {
public void processCustomer(int id, Consumer makeCustomerHappy) {
Customer customer = Database.getCustomerWithId(id);
makeCustomerHappy.accept(customer);
}
static private class Customer {
}
static private class Database {
static Customer getCustomerWithId(int id) {
return new Customer();
}
}
public static void main(String[] args) {
new OnBankLambda().processCustomer(100, (Customer customer) -> System.out.println("hello"));
}
}
观察者模式###
public interface Observer {
void notify(String msg);
}
public class A implements Observer{
@Override
public void notify(String msg) {
if (msg!=null && msg.contains("money")) {
System.out.println("A money");
}
}
}
public class B implements Observer {
@Override
public void notify(String msg) {
if (msg!=null && msg.contains("queen")) {
System.out.println("B queen");
}
}
}
public class C implements Observer{
@Override
public void notify(String msg) {
if (msg!=null && msg.contains("wine")) {
System.out.println("C wine");
}
}
}
public interface Subject {
void registerObserver(Observer observer);
void notifyObserver(String msg);
}
public class Feed implements Subject {
private final List observers=new ArrayList<>();
@Override
public void registerObserver(Observer observer) {
this.observers.add(observer);
}
@Override
public void notifyObserver(String msg) {
observers.forEach(observer -> observer.notify(msg));
}
public static void main(String[] args) {
Feed feed=new Feed();
feed.registerObserver(new A());
feed.registerObserver(new B());
feed.registerObserver(new C());
feed.notifyObserver(" queen ,can you lend me some money ");
}
责任链模式###
传统的:
public abstract class ProcessingObject {
protected ProcessingObject successor;
public void setSuccessor(ProcessingObject successor) {
this.successor = successor;
}
public T handle(T input) {
T r=handleWork(input);
if(successor!=null){
return successor.handle(r);
}
return r;
}
abstract protected T handleWork(T input);
}
public class SpellCheckerProcessing extends ProcessingObject {
@Override
protected String handleWork(String input) {
return input.replaceAll("labda", "lambda");
}
}
public class HeaderTextProcessing extends ProcessingObject {
@Override
protected String handleWork(String input) {
return "HanderTextProcessing"+input;
}
}
public static void main(String[] args) {
ProcessingObject p1=new HeaderTextProcessing();
ProcessingObject p2=new SpellCheckerProcessing();
p1.setSuccessor(p2);
String result=p1.handle("labda labda ok ok ");
System.out.println(result);
}
Lambda简洁代码:
UnaryOperator header=(String text) -> "from header"+text;
UnaryOperator spell=(String text) -> text.replaceAll("labda", "lambda");
Function line=header.andThen(spell);
String result2=line.apply("labda labda ok ok");
System.out.println(result2);
public class ProduceMain {
static interface Product{}
static private class Loan implements Product{}
static private class Stock implements Product{}
static private class Bond implements Product{}
final static private Map> mapProducts=new HashMap<>();
static{
mapProducts.put("loan", Loan::new);
mapProducts.put("stock", Stock::new);
mapProducts.put("bond", Bond::new);
}
static private class ProduceFactory{
public static Product creatProduct(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);
}
}
public static Product createProductLambda(String name){
Supplier pSupplier=mapProducts.get(name);
if (pSupplier!=null) {
return pSupplier.get();
}
throw new RuntimeException("No such product "+name);
}
}
public static void main(String[] args) {
Product p1=ProduceFactory.creatProduct("loan");
Supplier loanSupplier=Loan::new;
Product p2=loanSupplier.get();
Product p3=ProduceFactory.createProductLambda("xyyy");
System.out.println(p1);
System.out.println(p2);
System.out.println(p3);
}
}
学会使用peek做调试,一个简单的demo如下:
List numbers=Arrays.asList(1,4,6,7,14);
numbers.stream().peek(x -> System.out.println(x))
.map(x -> x+10)
.peek(x -> System.out.println("after:"+x))
.collect(toList());