单例设计模式
单例设计模式主要用于当实例化对象消耗大量的时间和资源时。为了减少实例化对象带来资源和时间的浪费,我们采取只实例化一次对象的方法,这个方法就是单例设计模式。单例设计模式分为两种,懒汉式和饿汉式
饿汉式
饿汉式顾名思义,非常饥饿,必须马上给他new一个对象。当类初始化完毕就已经实例化好了一个对象。
Test.class
class Test{
/*
*私有化的构造方法
*/
private Test(){
}
private static Test t = new Test(); //马上new,饿汉式
public static Test getInstacne(){
return t;
}
}
Single.class
class Single{
public static void main(String[] args){
//Test t = new Test()构造方法私有化,不能直接new
Test t = Test.getInstance();
Test t2 = Test.getInstance();//以后的实例都指向我们第一次new的对象
Test t3 = Test.getInstance();
}
}
懒汉式
与饿汉式单例模式不同的是,懒汉式当类加载完毕并没有马上new对象,而是当被调用才new对象
Test1.class
class Test{
/*
*私有化的构造方法
*/
private Test1(){
}
private static Test1 t = null; //懒汉式
public static Test1 getInstacne(){
if (t == null){
Test1 t = new Test1()
}
return t;
}
}
Single.class
class Single{
public static void main(String[] args){
//Test t = new Test()构造方法私有化,不能直接new
Test1 t = Test.getInstance(); //第一次是new Test
Test1 t2 = Test.getInstance();//以后的实例都指向我们第一次new的对象
Test1 t3 = Test.getInstance();
}
}
单例设计模式适用于当我们创建对对象会消耗大量的资源,或者创建对象会浪费大量的时间所使用的。