锐智互动软件开发公司
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;

}

}


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

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

锐智互动软件品牌隶属于北京锐智互动网络科技有限公司,上海设有分支机构上海锐智开高数字科技有限公司。团队深耕企业级软件定制开发领域 11 年,拥有成熟的项目管理与落地实施能力,业务重点布局北京、上海、广州、深圳,服务覆盖全国及海外。依托物联网、AI 大模型等前沿技术能力,可完成 APP、小程序、网页端系统全品类定制开发;聚焦教育、医疗、生产制造、新能源、新零售五大行业,致力于为企业打造高可用、可扩展的定制化软件系统与数字化解决方案。

咨询热线:400-1050-360

推荐阅读

从模板到定制:小程序、APP、软件开发避坑科普指南 Tag: 北京小程序app软件定制开发公司 企业数字化开发科普:软件定制、小程序、APP 开发全解析 Tag: 北京医疗小程序app定制开发公司 2026 年 09 月北京物联网 IoT 软件开发费用解析 Tag: 北京物联网开发公司 2026 年 09 月北京客户管理系统 CRM 软件开发的流程和周期 Tag: 北京 CRM 软件开发 2026年上海CRM定制开发公司哪家不错?四家头部服务商深度对比 Tag: 上海CRM定制开发 2026年8月上海物联网IoT定制开发公司售后服务评估 Tag: 上海物联网开发 2026年上海软件定制开发公司哪家专业?全流程服务与售后保障解析 Tag: 上海软件定制开发公司推荐 2026年上海IoT物联网系统定制开发周期与案例深度解析 Tag: 上海IoT物联网系统定制开发公司 2026年上海CRM企业管理系统软件开发公司推荐与实力对比 Tag: 上海CRM系统软件开发公司

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

立即咨询