java单例模式(下)

五种实现方式:


//create instance with loading class.it's better to create instance the when you// will use.the instance should not be heavy and use possiblely.



在类加载到jvm初始化的时候创建对象,如果实例比较大,会影响性能。

class Singleton1{

private static final Singleton1 instance = new Singleton1();
private Singleton1(){

}
public static Singleton1 getInstance(){
return instance; 
}
}


//double check. 对Singleton2的class对象加锁。
class Singleton2{
private static Singleton2 instance;
private Singleton2(){

}
public static Singleton2 getInstance(){
if(instance == null){
synchronized(Singleton2.class){
if(instance == null){
instance = new Singleton2();
}
}
}
return instance;
}

}
//静态内部类使用,延迟实例化对象。在使用时创建而不是在类加载初始化创建。
class Singleton3{
private Singleton3(){
}
private static class Instance{
private static final Singleton3 instance = new Singleton3();
private Instance(){}
}
public static Singleton3 getInstance(){
return Instance.instance;
}
}
//can't clone and serializable.recommend use. 避免克隆和反序列化得到不同实例对象。
enum Singleton4{
INSTANCE;
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}
//use in single thread 适用单线程
class Singleton5{
private static Singleton5 instance;
private Singleton5(){

}
public static Singleton5 getInstance(){
if(instance == null){
instance = new Singleton5();
}
return instance;
}
}
同步方法性能受到影响,适用于调用次数不多的情况。
class Singleton6{
private static Singleton6 instance;
private Singleton6(){

}
public static synchronized Singleton6 getInstance(){
if(instance == null){
instance = new Singleton6();
}
return instance;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值