锐智互动软件开发公司
400-1050-360
软件开发 APP开发 微信/小程序开发 大型电商平台开发 数据挖掘
400-1050-360
软件开发 APP开发 微信/小程序开发 大型电商平台开发 数据挖掘

软件开发公司 > 动态 > 软件开发

Java设计模式之单例模式-北京软件开发公司

软件开发 - 2020 - 07 - 08 软件开发 软件开发公司 北京软件开发



1、饿汉式

1)简单的饿汉式:

Public class ehanshiSingleton{

     Private ehanshiSingleton(){

}

     Private final static ehanshiSingleton  h = new ehanshiSingleton();

     Public static ehanshiSingleton getSingleton(){

         Return lhanshiSingleton.h;

}

}

imgs/rzhd/ueditor/jpg15942019685179660.jpg

2)静态代码写法:

Public class ehanshiSingleton{

     Private ehanshiSingleton(){

}

     Private final static ehanshiSingleton  h;

     Static{

     h=ehanshiSingleton();

}

     Public static ehanshiSingleton getSingleton(){

         Return lhanshiSingleton.h;

}

}


以上两种写法执行是一样的,在类初始化是建立一个对象,当调用静态方法时返回同一个对象的实例,符合单例设计的设计思想,如使用较多的情况下会消耗很多资源;有些单例类使用较少,造成资源浪费;


2、懒汉式

1)简单的懒汉式:

Public class lhanshiSingleton{

     Private lhanshiSingleton(){

}

     Private static lhanshiSingleton  lanhanshiSingleton;

     Public static lhanshiSingleton getSingleton(){

        If(lanhanshiSingleton==null){

             Return new lhanshiSingleton();

}

        Return lanhanshiSingleton;

}

}



2)加锁后的懒汉式:

Public class lhanshiSingleton{

     Private lhanshiSingleton(){

}

     Private static lhanshiSingleton  lanhanshiSingleton;

     Public static synchronized lhanshiSingleton getSingleton(){

        If(lanhanshiSingleton==null){

             Return new lhanshiSingleton();

}

        Return lanhanshiSingleton;

}

}


3)双重检查锁懒汉式:

Public class lhanshiSingleton{

     Private lhanshiSingleton(){

}

     Private static lhanshiSingleton  lanhanshiSingleton;

     Public static lhanshiSingleton getSingleton(){

       Synchronized(lhanshiSingleton.class){

         If(lanhanshiSingleton==null){

           Return new lhanshiSingleton();

}

            

}

        Return lanhanshiSingleton;

}

}


以上便是单例模式的基本写法;

下一章:在线教育软件开发有哪些独特的优势?北京软件开发公司
软件开发
关于锐智互动

锐智互动网络科技遵循严格的质量和安全标准, 实施严密的安全措施, 拥有成熟可靠的管理和开发流程, 公司凭借多年的行业积累、深厚的 行业专长和成熟的行业实践,为客户持续创造关键价值。我们始终关 注前沿技术,保持国际领先的眼界和技术储备。公司自 成立以来, 在团队成员的共同努力下,已经成功服务于上百家企业,其中包括 我爱我家、联东集团、优财CMA、5100、奔驰、华为、伊利、宝马、 迪思公关、航天国旅、HOTWIND、北京电通等众多知名企业。

咨询热线:400-1050-360

推荐阅读

在软件开发定制中,如何确保项目按时交付? Tag: 软件开发定制 软件开发定制的流程是什么样的? Tag: 软件开发定制 软件开发定制的优势有哪些? Tag: 软件开发定制 为什么在软件开发中需要定制化解决方案? Tag: 软件开发 什么是软件开发定制? Tag: 软件开发定制 软件定制开发公司与外包公司有什么区别? Tag: 软件定制开发公司 如何评估一家软件定制开发公司的能力? Tag: 软件定制开发公司 软件定制开发公司的价格如何确定? Tag: 软件定制开发公司 如何选择一家靠谱的软件定制开发公司? Tag: 软件定制开发公司

提交需求,获取工期与报价

立即咨询