单例模式
// 饿汉式 第一种
public class Singleton1 {
private Singleton1(){}
public static final Singleton1 INSTANCE = new Singleton1();
}
public enum Singleton2 {
INSTANCE;
}
import java.io.IOException;
import java.util.Properties;
//静态方法加载
public class Singleton3 {
private Singleton3(String 单例){}
public static Singleton3 INSTANCE;
static {
Properties properties = new Properties();
try {
properties.load(Singleton3.class.getClassLoader().getResourceAsStream("路径文件"));
INSTANCE = new Singleton3(properties.getProperty("单例"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 懒汉式 线程 不安全
public class Singleton4 {
private Singleton4(){}
private static Singleton4 INSTANCE;
public static Singleton4 getInstance(){
if (INSTANCE==null){
INSTANCE = new Singleton4();
}
return INSTANCE;
}
}
public class Singleton5 {
private Singleton5 (){}
private static Singleton5 INSTANCE ;
public static Singleton5 getINSTANCE(){
synchronized (Singleton5.class){
if (INSTANCE==null){
INSTANCE = new Singleton5();
}
}
return INSTANCE ;
}
}
/*
在内部类比诶加载和初始化时,才创建INSTANCE的实例对象
静态内部类不会自动随着外部类的加载和初始化而初始化 它是要加载和初始化
因为是在内部类加载和初始化 创建 因此线程是安全的
*/
public class Singleton6 {
private Singleton6(){}
private static class Inner{
public static final Singleton6 INSTANCE = new Singleton6();
}
public static Singleton6 getInstance (){
return Inner.INSTANCE;
}
}
answer: 5 1 10 6 9 3 2 9 8 7
9 3 2 9 8 7 ;
答案解析
public int f (int n){
if (n<=2&&n>0) return n;
return f(n-1)+f(n-2);
}
public static int f2 (int n){
int i = 1;
int j = 2 ;
int sum = 2;
if (n<=2&&n>0) return n;
int counter = 3;
while (counter<=n){
j = i; // 记录 count 1的值
i = sum;// count 2 的值
sum = i+j; //获得 count3 的值
counter++;
}
return sum;
}
6
加上this 指的就是 上面的成员变量 ,不加this指的是 局部变量
7
8
Redis