所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例。
1.饿汉式
- 坏处:对象加载时间过长。
- 好处:饿汉式是线程安全的
代码示例:
//饿汉式
public class SingletonPattern01 {
//1.内部创建类的对象,此对象也必须声明为静态的
private static SingletonPattern01 singleton = new SingletonPattern01();
//2.私有化类的构造器
private SingletonPattern01(){
}
//3.提供公共的静态的方法,返回类的对象
public static SingletonPattern01 getInstance(){
return singleton;
}
}
class MainTest{
public static void main(String[] args) {
SingletonPattern01 instance1 = SingletonPattern01.getInstance();
SingletonPattern01 instance2 = SingletonPattern01.getInstance();
System.out.println(instance1 == instance2);
}
}
输出结果:
true
Process finished with exit code 0
2.懒汉式
2.懒汉式
好处:延迟对象的创建。目前的写法坏处:线程不安全。(可以转变成线程安全的,这里暂且先不提)
代码示例:
public class SingletonPattern02 {
//1.声明当前类对象,没有初始化,此对象也必须声明为static的
private static SingletonPattern02 singleton = null;
//2.私有化类的构造器
private SingletonPattern02(){
}
//3.声明public、static的返回当前类对象的方法
public static SingletonPattern02 getInstance(){
if(singleton == null){
singleton = new SingletonPattern02();
}
return singleton;
}
}
class MainTest1{
public static void main(String[] args) {
SingletonPattern02 instance1 = SingletonPattern02.getInstance();
SingletonPattern02 instance2 = SingletonPattern02.getInstance();
System.out.println(instance1 == instance2);
}
}
输出结果:
true
Process finished with exit code 0