1 实现方式一:
class Husband{
//提供一个静态私有属性来保存单例
private static Husband hh=null;
//将构造方法私有化,杜绝在类以外的地方创建对象
private Husband(){}
//提供静态方法获取单例
//synchronized 同时,相当于一把锁,在这个进程执行完以下
//方法前,不会有其他并发进程挤上来。保证了共享数据的安全
//缺点是:性能下降
public static synchronized Husband getInstance(){
if(hh ==null){
hh = new Husband();
}
return hh;
}
}
public class TestSingleton {
public static void main(String[] args) {
Husband h1 = Husband.getInstance();
Husband h2 = Husband.getInstance();
System.out.println(h1==h2);
}
}
2 实现方式二
package day09.sta;
//考虑进程并发的安全性,这种模式的单例模式书写方式比之前更好
class Wife{
//3 定义一个静态属性存放单例
private static Wife ww =new Wife();
//1 构造方法私有化
private Wife(){}
//2 静态方法返回一个实例对象
public static Wife getInstangce(){
return ww;
}
}
public class TestSingleton2 {
public static void main(String[] args) {
Wife w1 = Wife.getInstangce();
Wife w2 = Wife.getInstangce();
System.out.println(w1==w2);
}
}
网友评论