带着问题去看单例模式
1、什么是单例模式?
2、单例模式有什么用?
3、怎么实现单例模式?
/**
* 饿汉模式
*/
public class SingletonHungry(){
private SingletonHungry(){}
private static SingletonHungry singleton=new SingletonHungry();
public static SingletonHungry newSingleton(){
return singleton;
}
}
/**
* 懒汉模式
*/
public class SingletonFull(){
private SingletonFull(){}
private static SingletonFull singleton=null;
public static SingletonFull newSingleton(){
if(singleton ==null)
singleton = new SingletonFull();
return singleton;
}
}
注意区别:1、效率问题
2、线程安全问题
本文介绍了单例模式的概念及其应用场景,并提供了两种实现方式:饿汉模式和懒汉模式。通过对比这两种模式,帮助读者理解单例模式的效率及线程安全问题。
1887

被折叠的 条评论
为什么被折叠?



