Java中static关键字的应用——单例设计模式

举报
YuShiwen 发表于 2022/03/31 01:19:58 2022/03/31
1k+ 0 0
【摘要】 所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例。 1.饿汉式 坏处:对象加载时间过长。好处:饿汉式是线程安全的 代码示例: //饿汉式 public ...

所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例。

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.懒汉式

  • 好处:延迟对象的创建。
  • 目前的写法坏处:线程不安全。(可以转变成线程安全的,这里暂且先不提)

代码示例:

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
  
 

文章来源: blog.csdn.net,作者:Mr.Yushiwen,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/MrYushiwen/article/details/109743789

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。