设计模式:单例
来源:互联网 发布:德国电子地图软件 编辑:程序博客网 时间:2024/04/28 21:13
个人认为java中的各种常用设计模式很重要,所以把一些自己理解的东西写下来。
单例模式主要作用是保证在Java应用程序中,一个类Class只有一个实例在。 使用单例模式的好处还在于可以节省内存,因为它限制了实例的个数,有利于Java垃圾回收。
主要分两种:
1.饿汉式
方案1:
class Singleton { private static Singleton instance=new Singleton(); private Singleton(){} static Singleton getInstance() { return instance; }}
方案1中创建instance对象时无法传入参数,所以应用有限。
方案2:
class Singleton { private static class SingletonHolder { static final Singleton instance = new Singleton(); } public static SingletonKerriganF getInstance() { return SingletonHolder.instance; }}
方案2解决了方案1的缺陷。
2.懒汉式
方案1:
class Singleton { private static Singleton instance=null; private Singleton(){} static Singleton getInstance() { if(instance==null) instance=new Singleton(); return instance; }}
方案1中如果两个线程并发调用,假设线程一先判断完instance是否为null,然后准备执行new Singleton()。此刻线程二进入到判断instance是否为null,由于线程一还没执行nenew Singleton()方法,所以instance仍然是空的,因此线程二执行了new Signleton操作,就会出现了两个instance对象。
方案2:
public class Singleton { private static Singleton instance = null; public static Singleton getInstance() { synchronized (Singleton.class) { if (instance == null) { instance = new (); } } return instance; }}
方案2解决了方案1中的同步问题。
其中方案1是网上搜到的面试题的答案,方案2是自己的一些理解。
- 设计模式--单例
- 单例设计模式
- 设计模式----单例
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 设计模式-单例
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- cocos2dx 与android函数的相互调用及使用jni
- java中静态变量
- String、StringBuffer、StringBuilder的区别
- 科技论文写作1
- 网卡和网卡的驱动程序
- 设计模式:单例
- 全局变量和局部变量在内存里的区别
- Windows下声音出问题,linux没问题
- C++ public private protected三种继承区别
- hdu 4394 - Digital Square (dfs or bfs)
- 静态类数据成员、const与类
- MVC中使用EF(5):在 ASP.NET MVC 程序使用Entity Framework读取关联数据
- LA 6135 - Environment Protection simpson积分
- TCP为什么要三次握手,不是两次四次?