单例模式就是你不用再去new对象,而是有你调用函数,函数中去帮你创建对象,为什么不自己new呢,要调用函数不是麻烦了吗?
因为你每次new对象的时候,虽然都是同一个类的对象,但你每次new的时候,在内存中都每个你new对象对相应内存空间是不一样的,也就是说会占用多个内存空间,但是如果每次申请对象的时候先判断该对象是否存在,如果存在就使用这个对象,那这样的话就节省内存空间,但你每次想申请对象的时候不能都写一堆代码去判断对象是否存在,所以就写成一个函数,函数功能判断对象是否存在,存在就返回现有对象,不存在就创建一个对象返回,也就是所谓的单例模式。
单例模式很简单,也很复杂,看一看例子吧
下面给一个基础的例子
public class test {
private static test instance = new test();
private test(){}; //构造函数为 private,该类就不能被实例化
public static test getinstance()
{
return instance;
}
public void test_fun()
{
System.out.println("实例化成功");
}
}
public class test_demo {
public static void main(String [] args)
{
//test t = new test(); 不可以,因为test函数的构造函数为private,所以不能实例化
//应该这么用
test t = test.getinstance();
t.test_fun();
}
}
输出结果为实例化成功
单例实现有好多种方法,所以说有点复杂。
第一个 懒汉式:线程不安全
public class test {
private static test instance ;
private test(){}; //构造函数为 private,该类就不能被实例化
public static test getinstance()
{
if(instance == null)
{
instance = new test();
}
return instance;
}
}
这种比较简单,但是是线程不安全的,因为方法没有加锁,不支持多线程
第二种 懒汉式:线程安全
public class test {
private static test instance ;
private test(){}; //构造函数为 private,该类就不能被实例化
public static synchronized test getinstance()
{
if(instance == null)
{
instance = new test();
}
return instance;
}
}
就是在上一方法上的getinstance方法上加了一个synchronized关键字,加锁功能,但是加锁解锁本身很浪费效率,所以这个线程安全,但是效率可能差一点
第三种 饿汉式
public class test {
private static test instance = new test();
private test(){}; //构造函数为 private,该类就不能被实例化
public static test getinstance()
{
return instance;
}
}
这种方法不加锁,所以效率提高,但是每次类加载的时候就执行创建对象操作,浪费内存
第四种 双重校验锁
public class test {
private volatile static test instance ;
private test(){}; //构造函数为 private,该类就不能被实例化
public static test getinstance()
{
if (instance == null) {
synchronized (test.class) {
if (instance == null) {
instance = new test();
}
}
}
return instance;
}
}