为啥叫单例?
- 首先要明确一点,一般说new对象,每次new出来的对象都需要一块新的内存区域,new的次数内存占用呈正比。
- 现在有这么一种场景:我需要经常获取某个类的实例(大家公用的),与其每次使用的时候都要new,不如一直让它存在。
- 那么怎么保证这个“单”字呢? 也就是怎么防止new呢?
单例三板斧
- 构造函数-------私有化private(在别的类中没法new了)
- 本类中new一个对象(这个就是唯一的种子,所有人都用它)
- 别人怎么拿到这个对象呢? 别急, 本类中提供一个公共的方法,把2中new出来的对象丢给您。
代码样例(饿汉式)
class Single
{
public static void main(String[] args)
{ //下面这个不注掉的话,会报错的
//DaLong d = new DaLong();
DaLong d = DaLong.getInstance();
System.out.println("大龙刷新后的血量值是:" + d.hp);
}
}
class DaLong
{
int hp = 8000;
//三板斧 第一式,别想new DaLong类的实例出来
private DaLong(){
}
//三板斧 第二式,唯一的种子在俺这儿
private static DaLong s = new DaLong();
//三板斧 第三式,获取种子(实例)的方法在这
public static DaLong getInstance(){
return s;
}
}
至于为啥叫饿汉式?第二式中 private static DaLong s = new DaLong(); 对象s随类的加载就产生了,太猴急了,所以叫饿汉
懒汉式样例
class Single
{
public static void main(String[] args)
{
//DaLong d = new DaLong();
DaLong d = DaLong.getInstance();
DaLong f = DaLong.getInstance();
if (d == f)
{
System.out.println("d == f" );
}
}
}
class DaLong
{ //1
private DaLong(){}
//2
private static DaLong s = null;
public static DaLong getInstance(){
if (s == null){
//3
s = new DaLong();
}
return s;
}
}
还是用的三板斧,为啥就叫懒汉了? 因为懒啊, 等到发现这个对象是null的时候才晓得new,你是有多懒。