单例模式详解
来源:互联网 发布:阿里云好还是腾讯云好 编辑:程序博客网 时间:2024/06/05 21:18
一、概念
1. java中单例模式是一种常见的设计模式,单例模式分三种:懒汉式单例、饿汉式单例、双重锁单例三种。
二、单例模式的特点:
① 单例类只能有一个实例。
② 单例类必须自己创建自己的唯一实例
③ 单例类必须给所有其他对象提供这一实例
三、单例代码
懒汉模式:
<span style="font-size:18px;">package com.test;public class Singleton {public static Singleton instance = null;public static synchronized Singleton Instance(){if(instance == null){instance = new Singleton();}return instance;}private Singleton(){};}</span>
饿汉模式
<span style="font-size:18px;">public class Singleton{ //在自己内部定义自己的一个实例,只供内部调用 private static final Singleton instance = new Singleton(); private Singleton(){ //do something } //这里提供了一个供外部访问本class的静态方法,可以直接访问 public static Singleton getInstance(){ return instance; }}</span>
双重锁
<span style="font-size:18px;">public class Singleton{ private static Singleton instance=null; private Singleton(){ //do something } public static Singleton getInstance(){ if(instance==null){ synchronized(Singleton.class){ if(instance==null){ instance=new Singleton(); } } } return instance; }} <code class="c# comments">//这个模式将同步内容下方到if内部,提高了执行的效率,不必每次获取对象时都进行同步,只有第一次才同步,创建了以后就没必要了。</code></span>
0 0
- 单例模式详解
- 单例模式详解
- 单例模式详解
- 单例模式详解
- 单例模式详解
- 单例模式详解
- 单例模式详解
- 单例模式详解
- 单例模式详解
- 详解单例模式
- 单例模式详解
- 单例模式详解
- 详解【单例模式】
- 单例模式 详解
- 单例模式详解
- 单例模式详解
- 单例模式详解
- 详解单例模式
- Financial application- computing future tuition
- Java 之EnumSet与EnumMap
- 浅谈ssh(spring+struts+hibernate)框架的搭建
- nginx使用zookeeper造成进程死锁和崩溃问题和解决方案
- 序列化与反序列化 Socket中处理方法
- 单例模式详解
- swoole1.8.0+版本异步redis安装(本实例为swoole1.8.10版本)详解
- 设置Android studio 禁用sdk检查更新
- VS2015使用小技巧 查看值类型int与引用类型string在栈中的地址、堆中的地址
- H5 canvas绘图描边小细节
- 单例模式三种模式,饿汉、饱汉、双重锁模式,实例及优劣详解
- cannot import name imread
- 移动端meta常用参数
- Cygwin (64-bit)绿色版