学习的第35天。
总结:
单例模式:
饿汉式:天生线程安全(无锁),类加载时创建(不用的时候,也被迫创建了,占用资源)
饿汉式
class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
懒汉式1:天生线程不安全(需要后加锁) ,使用时创建
懒汉式1
class Singleton{
private static Singleton instance =null;
private Singleton(){}
public synchronized static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
懒汉式2:
懒汉式2
class Singleton{
private Singleton(){}
private static class Holder {
static Singleton instance = new Singleton();
}
public static Singleton getInstatnce(){
return Holder.instance;
}
}
Lambda:
概念:允许把函数作为一个方法的参数。(函数作为参数传递到方法中)
<函数式接口> <变量名> = (参数1,参数2……)->{ 方法体 }
形参列表的数据类型会自动推断;形参列表为空,只需保留();形参列表只有一个()可以省略,只需参数名字也行
如果执行语句只有一句,且无返回值,{}可以省略。若有返回值,扔向省略{},return也省略。保证执行语句只有1句
函数式接口:
如果一个接口只有一个抽象方法,则该接口称为函数式接口。
为了确保接口达到要求,可以添加@@FunctionalInterface注解
内置四个核心函数式接口:
Consumer<T> 消费型接口 ; void accept(T t);
Supplier<T> 供给型接口 : T get();
Function<T,R> 函数型接口 R apply(T t);
Predicate<T> 断雁行接口 boolean test(T t);
方法引用:
方法引用是Lambda 表达式的一种简写形式,如果Lambda表达式方法体中只是调用一个特定的已存在的方法,则可以使用方法引用。
使用:
类名::静态方法
类名::实例方法
类名::new
对象::方法名(常用)