设计模式 单例
来源:互联网 发布:云舒网络 拖欠工资 编辑:程序博客网 时间:2024/05/23 11:50
Singleton设计模式
1.使用时生成(非线程安全)
java code
class Singleton { private static Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; }}public class SingletonMode { public static void main(String[] args) { Singleton instance1 = Singleton.getInstance(); Singleton instance2 = Singleton.getInstance(); if (instance1 == instance2) { System.out.println("singleton"); } else { System.out.println("not singleton"); } }}
修改获得实例方法来保证线程安全
1 使用方法同步
java code
public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance;}
2 使用类实例同步
java code
public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { instance = new Singleton(); } } return instance;}
2.初始化加载(线程安全)
java code
class Singleton { private static final Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; }}public class SingletonMode { public static void main(String[] args) { Singleton instance1 = Singleton.getInstance(); Singleton instance2 = Singleton.getInstance(); if (instance1 == instance2) { System.out.println("singleton"); } else { System.out.println("not singleton"); } }}
0 0
- 设计模式--单例
- 单例设计模式
- 设计模式----单例
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 设计模式-单例
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- OC基础笔记3
- 用hashMap存储100个随机数
- 一、java系列maven学习:eclipse集成maven
- 一名3年工作经验的程序员应该具备的技能
- VMware虚拟机克隆Linux系统后找不到eth0网卡的问题
- 设计模式 单例
- OC基础笔记4
- 特殊字符实现icon功能
- 无偿翻译UE4英文文章
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- OC基础笔记5
- 匹配电话号码(基础代码)
- 详解spring 每个jar的作用
- HeadFirstC笔记_6 数据结构与动态存储:牵线搭桥