在很多设计模式中,我相信大多数程序猿最早接触的设计模式就是单例模式啦,当然了我也不例外。单例模式应用起来应该是所有设计模式中最简单的。单例模式虽然简单,但是如果你去深深探究单例模式,会涉及到很多很多知识,我会继续更新这篇文章的。单例模式在整个系统中就提供了一个对象,然后整个系统都去使用这一个对象,这就是单例的目的。
一、饱汉式单例:
- public class Singleton {
- /**
- * 单例对象实例
- */
- private static Singleton instance = null;
- public static Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
- }
二、饿汉式单例:
- public class Singleton {
- /**
- * 单例对象实例
- */
- private static Singleton instance = new Singleton();
- public static Singleton getInstance() {
- return instance;
- }
- }
这两种单例在实际的代码中,往往是不能满足要求的,这就需要我们根据自己的需求来改写这些单例模式,
例如:如果创建的单例对象需要其他参数,这个时候,我们就需要这样改写:
- public class Singleton {
- /**
- * 单例对象实例
- */
- private static Singleton instance = null;
- public static Singleton getInstance(Context context) {
- if (instance == null) {
- instance = new Singleton(context);
- }
- return instance;
- }
- }
例如: 资源共享情况下,必须满足多线程的并发访问,这个时候,我们就应该这么做:
- public class Singleton {
- /**
- * 单例对象实例
- */
- private static Singleton instance = null;
- public synchronized static Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
- }
其实无论什么条件下,无论怎么改变,都是这两种单例模式的变种!!!!