package com.qiku.selfcheck; public class Singleton {
//饿汉式 只存在一个对象
//私有化构造器 这样就不能再外面new了
private Singleton(){ }
//2创建单例对象 4(加static 静态方法只能调用静态的对象或者属性)
private static Singleton instance=new Singleton();
//3提供一个公开的静态方法,发挥类的对象
public static Singleton getInstance() {
return instance;
} public static void main(String[] args) {
Singleton s1=getInstance();
Singleton s2= getInstance();
System.out.println(s1==s2);
}
}
对象名字不一样但是 地址是一样的
2.饿汉式package com.qiku.selfcheck;
public class Singleton2 {
//懒汉式
//1,私有化构造器
private Singleton2() {
}
//2 声明当前类对象 但没有初始化 4 static
private static Singleton2 instance=null;
//3提供公共的方法来调用
public static Singleton2 getInstance(){
if (instance==null){
instance= new Singleton2();
}
return instance;
}
public static void main(String[] args) {
Singleton2 s1=getInstance();
Singleton2 s2=getInstance();
System.out.println(s1==s2);
}
}
懒汉式体现了懒字 啥时候用啥时候创建对象
3.饿汉式和懒汉式的区别
饿汉线程安全,但是加载时间过长
懒汉非线程安全,但是延迟对象的创建
4、共同点
单例类只能有一个实例,单例类必须自己创建自己的唯一实例,单例类必须给所有其他对象提供这一实例。



