1.什么是单例设计模式?
使用单例设计模式,能够实现一个类只能有一个对象
2.怎么实现一个类只能有一个对象?
饿汉式(立即加载)
class Singleton{
private static final Singleton singleton = new Singleton();
private Singleton(){
}
publkic static Singleton getInstance(){
return singleton;
}
}
优点:不会出现多线程并发访问问题
缺点:对象太早的进内存,太晚消失,占内存
懒汉式(延迟加载)
方式一:
class Singleton{
private static Singleton sinleton;
private Singleton(){
}
publkic static Singleton getInstance(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
优点:对象不会太早的进内存,不占用内存
缺点:在多线程中,可能会创建出两个对象,就不构成单例了
方式二:
class Singleton{
private static Singleton sinleton;
private Singleton(){
}
publkic static synchronized Singleton getInstance(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
优点:不占内存,解决线程安全问题;
缺点:效率低了
方式三:(最终使用方式)
class Singleton{
private static Singleton sinleton;
private Singleton(){
}
publkic static synchronized Singleton getInstance(){
if(singleton == null){
synchronized (Singleton.class){
singleton = new Singleton();
}
}
return singleton;
}
}
优点:不占内存,解决线程安全引发的效率低的问题。
宁愿带着梦想前行,也不愿带着遗憾回道。请相信每一次努力都算数。