java面试题三

单例模式

1
2
3
4
5
6
7
8
9
10
11
饿汉式:
public class SingletonDemo{
//创建一个静态类对象
private static SingletonDemo instance = new SingletonDemo();
//修饰符限定为private,避免了类在外部被实例化
private SingletonDemo(){
}
public static SingletonDemo getInstance(){
return instance;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
懒汉式:
public class SingletonDemo{
private static SingletonDemo instance = null;
private SingletonDemo(){
}
public static synchronized SingletonDemo getInstance(){
if(instance == null){
instance = new SingletonDemo();
}
return instance;
}
}