Android开发中都会用到的一种最简单的设计模式,尤其是当初的面试中经常被问到的一种设计模式:
第二篇:单例模式
当需要控制一个类的实例只能有一个,而且客户只能从一个全局访问点访问它时,可以选用单例模式。
单例模式有两种:饿汉式与懒汉式。
1、饿汉式:
package com.hongri.singletonpattern;
/**
* 单例模式:
* 饿汉式(饿汉式是线程安全的)
* @author zhongyao
*/
public class Singleton2 {
private static Singleton2 uniqueInstance = new Singleton2();
/**
* 私有构造方法
*/
private Singleton2(){};
public static Singleton2 getInstance(){
return uniqueInstance;
};
}
双虚线上下分别是优化过的不同的懒汉式实现形式,可根据需要进行选择。
package com.hongri.singletonpattern;
/**
* 单例模式:
* 懒汉式(不加同步的懒汉式是线程不安全的)
* @author zhongyao
*/
public class Singleton {
private static Singleton uniqueInstance = null;
/**
* 私有构造方法
*/
private Singleton(){};
/**
* 虽然是线程安全的,但是会降低整个访问的速度
* @return
*/
public static synchronized Singleton getInstance(){
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
//=================================================================
/**
* "双重检查加锁":既可以实现线程安全,又能够使性能不受到很大的影响
*/
//对保存实例的变量添加volatile的修饰
private volatile static Singleton uniqueInstance = null;
private Singleton(){}
public static Singleton getInstance(){
//先检查实例是否存在,如果不存在才进入下面的同步块
if (uniqueInstance == null) {
//同步块,线程安全的创建实例
synchronized (Singleton.class) {
//再次检查实例是否存在,如果不存在才真正的创建实例
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
原文:http://blog.csdn.net/u012440207/article/details/45672691