单例模式
* 作用:保证整个应用程序中某个实例有且只有一个
* 类型:饿汉模式、懒汉模式
demo1:
package Singleton;
public class Singleton {
//将构造方法私有化,避免外部直接创建实例
private Singleton(){
}
//创建类的实例,使用 static
public static Singleton instance= new Singleton();
}
package Singleton;
public class testSingleton {
public static void testSingleton(){
Singleton instance1=Singleton.instance;
Singleton instance2=Singleton.instance;
if(instance1==instance2){
System.out.println("同一个实例");
}else{
System.out.println("不是同一个实例");
}
}
public static void main(String[] args) {
testSingleton();
}
}
运行结果:同一个实例
在这个demo1的基础上修改代码,使用一个public方法对象提供获取该实例的方法。
package Singleton;
public class Singleton {
//将构造方法私有化,避免外部直接创建实例
private Singleton(){
}
/*创建类的实例,使用 static
public static Singleton instance= new Singleton();*/
//创建类的实例,使用 static
private static Singleton instance= new Singleton();
//使用static即可在外部使用类名进行访问
public static Singleton getInstance(){
return instance;
}
}
public static void testSingleton2() {
Singleton instance1 = Singleton.getInstance();
Singleton instance2 = Singleton.getInstance();
if (instance1 == instance2) {
System.out.println("同一个实例");
} else {
System.out.println("不是同一个实例");
}
}
public static void main(String[] args) {
/*testSingleton();*/
testSingleton2();
}
}
运行结果:同一个实例
上述这个就是饿汉模式,在类加载时就创建了该类的唯一实例。
下面讲述懒汉模式
demo3
// 懒汉模式
private static Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
懒汉模式和饿汉模式的对比
饿汉模式在类的加载时就创建了一个实例,所以在加载的时候慢,获取的时候快
懒汉模式在类的加载时快,第一获取的时候需要创建对象,所以慢