1.恶汉模式(类进行加载的时候就已经生成了一个实例化对象)
空间换时间
package test;
class SingleOne{
public static int x=6;
private static SingleOne s=new SingleOne();
private SingleOne(){
}
public static SingleOne GetSingleOne() {
return s;
}
}
public class test{
public static void main(String[] args) {
System.out.println(SingleOne.GetSingleOne());
SingleOne ss=SingleOne.GetSingleOne();
SingleOne mm=SingleOne.GetSingleOne();
System.out.println(ss);
System.out.println(mm);
}
}
2.懒汉式(只有在调用方法时,才生成实例化对象)
时间换空间
package test;
class SingleOne{
public static int x=6;
private static SingleOne s=null;
private SingleOne(){
}
public static SingleOne GetSingleOne() {
if(s==null)#必须要判断,才只能生成一个
s=new SingleOne();
return s;
}
}
public class test{
public static void main(String[] args) {
System.out.println(SingleOne.GetSingleOne());
SingleOne ss=SingleOne.GetSingleOne();
SingleOne mm=SingleOne.GetSingleOne();
System.out.println(ss);
System.out.println(mm);
}
}
单例模式的缺点:
1.扩展比较困难
2.如果实例化后的对象长期不利用,系统将默认为垃圾进行回收,造成对象状态的丢失