一):饿汉式:在定义Singleton的时候就已经准备好了一个Singleton实例化对象INSTANCE,而并没有关心这个对象INSTANCE是否使用
public class Main {
public static void main(String[] args) {
Singleton s = null;
s = Singleton.getInstance();
s.print();
}
}
class Singleton{
private static final Singleton INSTANCE = new Singleton();
private Singleton(){}
public void print(){
System.out.println("hello,world");
}
public static Singleton getInstance(){
return Singleton.INSTANCE;
}
}
1)首先是构造函数必须私有化否则,可以实例化多个对象
Singleton s1 = new Singleton();
Singleton s2 = new Singleton();
2)既然是单例,则用static,所有实例共享一个对象,属性封装用private
3)然后定义一个返回static的属性的函数
二)懒汉式:
class Singleton{
private static Singleton instance=null;
private Singleton(){}
public void print(){
System.out.println("hello,world");
}
public static Singleton getInstance(){
if(Singleton.instance==null){
instance = new Singleton();
}
return instance;
}
}