两种单例模式的对比:
饿汉式:(真实开发的时候一般采用懒汉式)
1.class Single {//类一加载,对象就已经存在
private static Single s= new Single();
private =Single(){}
public stataic Single getInstance()
{
return s;
}
}
懒汉式(面试时一般会出这方式)
class Single2
{//类加载进来,没有对象,只有调用了getInstance方法
时才会创建对象
//延迟加载形式
pribvate static Single2 s= null;
private Single2(){}
public static Single2 getInstance(){
if(s==null)
s= new Single2();
return s;
}
}
单例模式三部曲:
1.通过new在本类中创建一个本类对象
2.私有化该类构造函数
3.定义一个公有的方法,将创建的对象返回
class ArrayToolDemo
{
public static void main(String args[]){
//Test t1=new Test();
//Test t2= new Test();
//采用单例模式式不同的调用方式:上面和下边
Test t1 = Test.getInstance();
Test t2 = Test.getInstance();
t1.setNum(10);
t2.setNum(20);
System.out.println(t1.getNum());
System.out.println(t2.getNum());
}
}
class Test{
private int num;
private static Test t = new Test();//通过new在本类中创建一个本类对象
private Test(){}//私有化该类构造函数
public static Test getInstance(){//.定义一个公有的方法,将创建的对象返回
return t;
}
public void setNum(int num){
this.num = num;
}
public int getNum(){
return num;
}
}