单例模式

1.饿汉模式
缺点:当加载该类时,静态方法也会被加载并生成一个对象占用内容,而这个对象不一定会使用,造成资源浪费;另外new SinletionTest()也无法获取构造函数异常;

public class SingletonTest {
    private SingletonTest(){}
    private static final SingletonTest instance = new SingletonTest();
    public SingletonTest getInstance()
        return instance;
    }
}

2.饱汉模式
解决了饿汉模式的缺点,但是当多线程时会引起冲突,比如第一个线程要获取对象时,if(instance ==null) 后,同时第二个线程进入判断并获取对象,而第一个线程继续执行会获取第二个对象,造成冲突

public class SingletonTest {
    private SingletonTest(){}
    private static SingletonTest instance = null;
    public SingletonTest getInstance(){
        if(instance == null) {
            instance = new SingletonTest();
        }
        return instance;
    }
}

3.解决上述问题只需要给函数添加一个锁就可以了,但是造成性能低下,因为成了多线程了;

public class SingletonTest {
    private SingletonTest(){}
    private static SingletonTest instance =null;
    public synchronized SingletonTest getInstance(){
        if(instance == null) {
            instance = new SingletonTest();
        }
        return instance;
    }
}
  1. 根据枚举设计单例模式(jdk1.6之后)
public enum SingleEnum {
    instance;
    public static void getInstance(){
        System.out.println("get123");
    }
}
//测试
public class TestEnum{
   public static void main(String args[]) {
     for(int i=0; i<10; i++){
          SingleEnum.instance.getInstance();
        }
    }
}
//打印结果
get123
get123
get123
get123
get123
get123
get123
get123
get123
get123
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值